Python: How to Swap Two Lists
There are several ways to swap elements between two lists.
- Swap using temporary variables.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
temp = list1
list1 = list2
list2 = temp
print(list1) # [4, 5, 6]
print(list2) # [1, 2, 3]
- Utilize multiple assignments for swapping:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1, list2 = list2, list1
print(list1) # [4, 5, 6]
print(list2) # [1, 2, 3]
Both methods can achieve the swapping of two lists, with the second method being more concise and elegant due to its use of multiple assignments.