Define a List and Swap the First and Last Elements
This Python code demonstrates how to define a list and swap the first and last elements of the list. Several implementations are provided, each achieving the same result.
Before Swap:
After Swap:
[3, 2, 1]
Example 1: Basic Swap Using a Temporary Variable
def swapList(newList): size = len(newList) # Swap first and last elements using a temporary variable temp = newList[0] newList[0] = newList[size - 1] newList[size - 1] = temp return newList # Define the list newList = [1, 2, 3] # Call the function and print the result print(swapList(newList))
Output:
[3, 2, 1]
Example 2: Pythonic Swap Using Tuple Assignment
def swapList(newList): # Swap first and last elements using tuple assignment newList[0], newList[-1] = newList[-1], newList[0] return newList # Define the list newList = [1, 2, 3] # Call the function and print the result print(swapList(newList))
Output:
[3, 2, 1]
Example 3: Swap Using a Tuple
def swapList(list): # Get first and last elements and swap them get = list[-1], list[0] list[0], list[-1] = get return list # Define the list newList = [1, 2, 3] # Call the function and print the result print(swapList(newList))
Output:
[3, 2, 1]
Explanation:
Example 1 swaps the first and last elements by using a temporary variable.
Example 2 demonstrates a more Pythonic way to swap using tuple assignment, which directly swaps the values without needing an additional variable.
Example 3 shows how to store the swapped elements in a tuple and then assign them back to their respective positions.
These implementations all result in the first and last elements of the list being swapped effectively.