Python program to interchange first and last elements in a list
In this tutorial, we will learn how to interchange or swap first and last element of a list in python.
This problem can be solved using basic techniques. This task asks you to interchange two elements of a list. Like array, each element of a list has a distinct position assigned to them starting from 0. Lists are mutable hence elements of the list can easily be replaced, new elements can be added or deleted from any position in the list. Also, lists accept all types of data types like integer, strings, etc.
Lists are written in square brackets. append() method is used to add new values in the list. Here is an example of list and appending new values to it:
list = ["code", "python", "codespeedy"] list.append("algorithm") print(list)
["code", "python", "codespeedy", "algorithm"]
Now, let us understand the code for this task.
Interchanging first and last elements of a list
Problem statement: Write a python program to interchange first and last elements in a list.
Logic: This problem follows a very simple logic. Let us see it in an ordered manner:
- First, save the first element of the list in a temporary variable storage.
- Next, replace the first element with the last element of the list.
- Finally, put the saved first element from the temporary variable in the last position.
- Make an empty list.
- Ask the user for the total number of elements in the list.
- Using the for loop take inputs for all the elements for the list and append them in the list.
- Display the current list for better comparison with the new one.
- Save the first element of the list in a temporary variable.
- Replace the first element with the last one.
- Now, take the first element that was stored in the temporary variable and replace it with the last element.
Program/Code: Swap first and last element in a list in Python
list =  n = int(input("Enter the number of elements in list:")) for x in range(0, n): element = input("Enter element:") list.append(element) print("Your current list is:", list) temp = list list = list[n-1] list[n-1] = temp print("New list is:", list)
Enter the number of elements in list:4 Enter element:1 Enter element:2 Enter element:3 Enter element:4 Your current list is: ['1', '2', '3', '4'] New list is: ['4', '2', '3', '1']
NOTE: There may be other possible methods to solve this problem.
You may also read:
can you explain these lines?
list = list[n-1]
list[n-1] = temp
List takes the first element in the list
list[n-1] takes the last element in a list
when we do these operations:
1. list = list[n-1]
list will store the last element value
2.list[n-1] = temp
last element will store the first elemnt value