Given a list, write a Python program to swap first and last element of the list.
Question
Given a list, write a Python program to swap first and last element of the list.
Solution
To swap the first and last elements of a list in Python, you can follow these steps:
- Define a list with some elements.
- Use indexing to access the first and last elements of the list.
- Assign the first element to a temporary variable.
- Assign the last element to the first position in the list.
- Assign the temporary variable to the last position in the list.
- Print the updated list to verify the swap.
Here's an example code snippet that demonstrates this:
# Step 1: Define a list
my_list = [1, 2, 3, 4, 5]
# Step 2: Access the first and last elements
first_element = my_list[0]
last_element = my_list[-1]
# Step 3: Assign the first element to a temporary variable
temp = first_element
# Step 4: Assign the last element to the first position in the list
my_list[0] = last_element
# Step 5: Assign the temporary variable to the last position in the list
my_list[-1] = temp
# Step 6: Print the updated list
print("Swapped list:", my_list)
Output:
Swapped list: [5, 2, 3, 4, 1]
In this example, the first element (1) and the last element (5) of the list are swapped, resulting in a new list [5, 2, 3, 4, 1].
Similar Questions
What will be the output of the following Python code?x = ['xy', 'za']for i in x: i.swapcase()print(x)
Complete this code to swap the first and last element of the given array. Do nothing if the array is empty.
How do you access the last element of a list in Python?Question 11Answerlist[-1]list[last]list[0]list[size-1]
Write a Python code snippet to swap the values of two variables without using a temporary variable
Given list [16, 32, 35, 99, 37, 42, 67, 88, 68], how many swaps are needed to sort the list?
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.