+ 1
Tuple Unpacking What is the value of
Please someone can help with this code: What is the value of y after this code runs? x, y = [1, 2] x, y = y, x The value of y?
3 Réponses
+ 3
In the first line, x and y are assigned the values from the list, in same order as they appear. So result:
x=1
y=2
In the next line x and y are assigned new values, the right side is a tuple, it could be written as:
x, y = (y, x)
And substituting the existing values:
x, y = (2, 1)
This is effectively swapping the values of the two variables.
So the result is
x=2
y=1
+ 2
You can copy the code to playground and check what happens!
0
with the same concept of substituion
x, y = [1, 2]
# the value of y here is 2 and x is 1
x, y = y, x
# after this operation the value of y == x = 1