JavaScript
x
7
1
lst = [0,1,2,3,4]
2
3
lst[0], lst[4] = lst[4], lst[0]
4
5
print(lst)
6
#[4, 1, 2, 3, 0]
7
But, when you assign them to a variable you get a different solution.
JavaScript
1
13
13
1
lst = [0,1,2,3,4]
2
x = lst[0]
3
y = lst[4]
4
5
x,y = y,x
6
7
print(lst)
8
#[0, 1, 2, 3, 4]
9
print(x)
10
# 4
11
print(y)
12
# 0
13
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:
JavaScript
1
4
1
a,b = 1,2
2
a,b = b,a
3
print(a,b) # 2,1
4
vs
JavaScript
1
6
1
a,b = 1,2
2
c,d = a,b
3
c,d = d,c
4
print(a,b) # 1,2
5
print(c,d) # 2,1
6
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.