Given a list, swap the first and the last elements of the list.
Input: [23, 100, 54, 56, 98]
Output: [98, 100, 54, 56, 23]
We will use a Python feature to solve this which assigns multiple variables at the same time.
For example, if we have variables a
and b
, then we can assign values to it like this:
a,b = 10,20
Where:
10
is stored in a
, and
20
is stored in b
.
#listlst = [23, 100, 54, 56, 98]#interchanging the first and last elementlst[0], lst[-1] = lst[-1], lst[0]print(lst)
In the following code snippet:
lst
with [23, 100, 54, 56, 98]
.lst[0], lst[-1] = lst[-1], lst[0]
, where with lst[-1]
, we can access last element.We will use a temporary variable to interchange the first and last elements in a list.
import java.util.*;class HelloWorld {public static void main( String args[] ) {//initialize the listint[] arr = {23, 100, 54, 56, 98};//temp variableint temp = arr[0];arr[0] = arr[arr.length-1];arr[arr.length-1] = temp;//printing modified arraySystem.out.println(Arrays.toString(arr));}}
In the following code snippet:
arr
with {23, 100, 54, 56, 98}
.arr[0]
in temp
.1
from the array length.temp
to the last element.