Python program to interchange first and last elements in a list

In this article, we will learn to interchange the first and last elements in a list using the python program.


Explanation

First, we make a function that swaps the elements.
Swap the first element by list[0] = list[n-1] and list[n-1] = list[n].


Program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# make a function to swap the elements
def swap(list, n):
    # swap the first element with last and last element with first elements
    list[0], list[n-1] = list[n-1], list[0]
    # return the list
    return list

# initilize the array
list = [13, 21, 24, 55, 64, 74]
n = len(list)

# print the result
print(swap(list, n))


Output

[74, 21, 24, 55, 64, 13]
Next Post Previous Post
No Comment
Add Comment
comment url