Skip to content
Advertisement

Why doesn’t parallel swapping work with variables in python?

lst = [0,1,2,3,4]

lst[0], lst[4] = lst[4], lst[0]

print(lst) 
#[4, 1, 2, 3, 0]

But, when you assign them to a variable you get a different solution.

lst = [0,1,2,3,4]
x = lst[0]
y = lst[4]

x,y = y,x

print(lst)
#[0, 1, 2, 3, 4]
print(x)
# 4
print(y)
# 0

My best guess is that it has something to do with were the variables are pointing to in memory.

Advertisement

Answer

I think the list is confusing you, so here is an equivalent example without a list:

a,b = 1,2
a,b = b,a
print(a,b) # 2,1

vs

a,b = 1,2
c,d = a,b
c,d = d,c
print(a,b) # 1,2
print(c,d) # 2,1

As I hope you can clearly see from the second piece of code, here we are have the values 1 and 2 in a and b respectively, and we are assigning them to c and d, and then swapping c and d. No where did we swap between a and b, so it remains a = 1 and b = 2. Only c and d were swapped.

Advertisement