How to swap positions of elements in a Python list?

In Python, there are various ways to swap the positions of elements in a list. Here are some commonly used methods:

  1. Swap using a temporary variable:
a = [1, 2, 3, 4]
temp = a[0]
a[0] = a[1]
a[1] = temp
print(a)  # 输出:[2, 1, 3, 4]
  1. Performing a swap using tuple unpacking:
a = [1, 2, 3, 4]
a[0], a[1] = a[1], a[0]
print(a)  # 输出:[2, 1, 3, 4]
  1. Exchange using the pop() and insert() methods of a list:
a = [1, 2, 3, 4]
a.insert(0, a.pop(1))
print(a)  # 输出:[2, 1, 3, 4]
  1. Exchange using slices
a = [1, 2, 3, 4]
a[0:2] = a[1::-1]
print(a)  # 输出:[2, 1, 3, 4]

You can use any of the methods above to swap the positions of elements in the list, just choose the one that works best for your situation.

bannerAds