Python Program to Swap the First and Last Element in a List

1. Introduction

Swapping elements in a list is a common operation that may be needed in various programming tasks such as algorithms and data manipulation. In Python, swapping is straightforward due to the ease of list indexing.

Definition

To swap elements means to interchange their positions within the list. Specifically, swapping the first and last element means the first element becomes the last, and the last element becomes the first.

2. Program Steps

1. Define a list of elements.

2. Use indexing to swap the first and last elements in the list.

3. Output the modified list.

3. Code Program

# Define a list of elements
my_list = [12, 35, 9, 56, 24]

# Swap the first and last element using a temporary variable
# Save the first element in a temporary variable
temp = my_list[0]

# Assign the last element's value to the first position
my_list[0] = my_list[-1]

# Assign the value of the temporary variable to the last position
my_list[-1] = temp

# Output the modified list
print(f"List after swapping the first and last elements: {my_list}")

# Alternatively, swap without using a temporary variable (Pythonic way)
my_list[0], my_list[-1] = my_list[-1], my_list[0]

# Output the list again to show it's back to the original
print(f"List after swapping back to original: {my_list}")

Output:

List after swapping the first and last elements: [24, 35, 9, 56, 12]
List after swapping back to original: [12, 35, 9, 56, 24]

Explanation:

1. my_list is initially defined with five integer elements.

2. temp is used to temporarily hold the first element of my_list, which is 12.

3. The last element of my_list (my_list[-1]) is placed in the first position (my_list[0]).

4. The value stored in temp is then assigned to the last position in my_list.

5. The first print statement shows my_list after the swap, with the first and last elements interchanged.

6. The alternative swapping method uses tuple unpacking to swap the elements back without a temporary variable, demonstrating a more Pythonic approach.

7. The second print statement confirms that the list has been swapped back to its original order.

Comments