How to Swap First and Last Value of a List in Python


In this example we will show how to exchange the first and last values of a list.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

def userList():
    n = int(input("Please input the number of elements: "))
    a = []
    for i in range(n):
        j = int(input("Please input the " + str(i + 1) + "th element: "))
        a.append(j)
    return a

a = userList()
print("The original list: ", a)
temp = a[0]
a[0] = a[-1]
a[-1] = temp
print("The new list: ", a)

Output:

Please input the number of elements:  4
Please input the 1th element: 12
Please input the 2th element: 56
Please input the 3th element: 23
Please input the 4th element: 89
The original list: [12, 56, 23, 89]
The new list: [89, 56, 23, 12]
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments