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

26th Jul 2022, 6:53 AM
MrFantastic
MrFantastic - avatar
7 Answers
+ 4
MrFantastic a = 2 b = 3 a,b = b,a print(a) #3 print(b) #2
26th Jul 2022, 8:01 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 3
Switching places.
26th Jul 2022, 7:32 AM
Mustafa A
Mustafa A - avatar
+ 3
MrFantastic swapping value without using 3rd variable. Rik Wittkopp Sorry wrong mentioned
26th Jul 2022, 8:07 AM
A͢J
A͢J - avatar
+ 3
A͢J No worries buddy 😁👍
26th Jul 2022, 9:51 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 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
26th Jul 2022, 12:58 PM
Sandeep
Sandeep - avatar
+ 2
Thanks everyone 😊
26th Jul 2022, 9:22 AM
MrFantastic
MrFantastic - avatar
0
Variable value switch places, i.e they get updated
28th Jul 2022, 2:20 AM
Coco
Coco - avatar