Python program to interchange first and last elements in a list

PythonServer Side ProgrammingProgramming

In this article, we will learn about the solution to the problem statement given below.

Problem statement − We are given a list, we need to swap the last element with the first element.

There are 4 approaches to solve the problem as discussed below−

Approach 1: The brute-force approach

Example

 Live Demo

def swapLast(List):
   size = len(List)
   # Swap operation
   temp = List[0]
   List[0] = List[size - 1]
   List[size - 1] = temp
   return List
# Driver code
List = ['t','u','t','o','r','i','a','l']
print(swapLast(List))

Output

['t','u','t','o','r','i','a','l']

Approach 2: The brute-force approach using negative indexes

Example

 Live Demo

def swapLast(List):
   size = len(List)
   # Swap operation
   temp = List[0]
   List[0] = List[-1]
   List[-1] = temp
   return List
# Driver code
List = ['t','u','t','o','r','i','a','l']
print(swapLast(List))

Output

['t','u','t','o','r','i','a','l']

Approach 3: The packing and unpacking of a tuple

Example

 Live Demo

def swapLast(List):
   #packing the elements
   get = List[-1], List[0]
   # unpacking those elements
   List[0], List[-1] = get
   return List
# Driver code
List = ['t','u','t','o','r','i','a','l']
print(swapLast(List))

Output

['t','u','t','o','r','i','a','l']

Approach 4: The packing and unpacking of a tuple

Example

 Live Demo

def swapLast(List):
   #packing the elements
   start, *middle, end = List
   # unpacking those elements
   List = [end, *middle, start]
   return List
# Driver code
List = ['t','u','t','o','r','i','a','l']
print(swapLast(List))

Output

['t','u','t','o','r','i','a','l']

Conclusion

In this article, we have learned about how we can interchange first and last elements in a list

raja
Published on 24-Dec-2019 10:01:58
Advertisements