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)

Output:

["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:

  1. First, save the first element of the list in a temporary variable storage.
  2. Next, replace the first element with the last element of the list.
  3. Finally, put the saved first element from the temporary variable in the last position.

Steps/Algorithm:

  1. Make an empty list.
  2. Ask the user for the total number of elements in the list.
  3. Using the for loop take inputs for all the elements for the list and append them in the list.
  4. Display the current list for better comparison with the new one.
  5. Save the first element of the list in a temporary variable.
  6. Replace the first element with the last one.
  7. 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[0]
list[0] = list[n-1]
list[n-1] = temp
print("New list is:", list)

Output:

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:

Leave a Reply

Your email address will not be published. Required fields are marked *