0
What does a,b = b,a do to the variable?
def myfunc(a,b): a,b = b,a ⬅️❔❔❔ if a==b and b==a: print('Different') elif a==b and b!=a: print('Same') else: print('DifSame') myfunc(2,3) Python challenge by Arash
7 odpowiedzi
+ 4
MrFantastic
a = 2
b = 3
a,b = b,a
print(a) #3
print(b) #2
+ 3
Switching places.
+ 3
MrFantastic
swapping value without using 3rd variable.
Rik Wittkopp Sorry wrong mentioned
+ 3
A͢J
No worries buddy
😁👍
+ 3
-> a, b = b, a
This seems simple but there are some steps involved that I think will be helpful to know.
To understand this, you need to understand two things:
1) In python, expressions are evaluated from left to right. In assignment, right hand side is evaluated first and then the left hand side.
2) You can create tuples without parentheses
x = (1,2)
y = 1, 2
both x and y above are tuples. x is created with parentheses compared to y. Whenever a value is separated by comma, it is evaluated as a tuple.
z = 1,
Here, z is also a tuple because comma.
________________________________________
Now to your question, say a = 1 and b = 2
...
-> a, b = b, a
can be written as
a, b = (b, a)
Since, right side is evaluated first, we can simplify it to:
a, b = (2, 1)
now, assignment will happen and a will be 2 and b will be 1.
this concept is known as 'tuple unpacking'. Taking the tuple on right side and assigning it to the variables on left.
For more info: https://www.w3schools.com/python/python_tuples_unpack.asp
+ 2
Thanks everyone 😊
0
Variable value switch places, i.e they get updated