Editor

Python Program to Swap the First and Last Elements of a List

Beginner · Lists

This program swaps the first and the last element of a list, so [12, 35, 9, 56, 24] becomes [24, 35, 9, 56, 12]. It uses index 0 for the first element and index -1 for the last, which works for a list of any length.

Program

swap_first_and_last.py
numbers = [12, 35, 9, 56, 24] # or: numbers = [int(x) for x in input("Enter numbers: ").split()]
print("Original list:", numbers)
if len(numbers) >= 2:
temp = numbers[0] # keep the first element safe
numbers[0] = numbers[-1] # -1 is the index of the last element
numbers[-1] = temp
print("After swapping:", numbers)
else:
print("The list needs at least two elements to swap")
Output
Original list: [12, 35, 9, 56, 24]
After swapping: [24, 35, 9, 56, 12]

How it works

  1. Index 0 is the first element, and index -1 always means the last element, whatever the length of the list.
  2. temp holds the first element, because the next line overwrites it.
  3. The last element is copied to the front, and then temp is copied to the back.
  4. A list with fewer than two elements has nothing to swap, so the program says so instead.

Other ways to write it

Swapping in one line

Swapping in one line
numbers = [12, 35, 9, 56, 24]
numbers[0], numbers[-1] = numbers[-1], numbers[0]
print("After swapping first and last:", numbers)
i, j = 1, 3 # any two positions can be swapped the same way
numbers[i], numbers[j] = numbers[j], numbers[i]
print(f"After also swapping positions {i} and {j}:", numbers)
Output
After swapping first and last: [24, 35, 9, 56, 12]
After also swapping positions 1 and 3: [24, 56, 9, 35, 12]

Python works out the right-hand side first and then assigns both values, so no temporary variable is needed.

Using pop(), insert() and append()

Using pop(), insert() and append()
numbers = [12, 35, 9, 56, 24]
first = numbers.pop(0) # take the first element out
last = numbers.pop() # take the last element out
numbers.insert(0, last)
numbers.append(first)
print("After swapping:", numbers)
Output
After swapping: [24, 35, 9, 56, 12]

Taking both ends out and putting them back the other way round gives the same result, though it does more work than a swap.

Try it yourself

Run the program with a one-element list, [7], to see the message.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises