Skip to content
Home » Python Programs » Python Program to Swap First and Last Element of List

Python Program to Swap First and Last Element of List

Simple python program to swap first and last element of list. In this program we can swap the first element and last of a list in python for beginners to understand the basic concept of programming.

Function Definition in Python

The keyword def is used to define a function. The name of the function is followed by the parameter(s) in (). The colon denotes the beginning of the function body, which is denoted by an indentation. The return statement determines the value to be returned inside the function body.

List Definition in Python

In Python, a list is a data structure that is a mutable (or changeable) ordered sequence of elements. A list’s items are the elements or values that make up the list. Lists are defined by values between square brackets [] in the same way that strings are defined by characters between quotes. Here we have used the list function to execute the python program to swap first and last element of list 

Python Program to Swap First and Last Element of List

def swap(new):
    size = len(new)
    temp = new[0]
    new[0] = new[size - 1]
    new[size - 1] = temp
    return new
new = [120, 335,239, 556, 224]
print(swap(new))

Output:

[224, 335, 239, 556, 120]