Python program to swap two variables in single line in python
Python program to swap two variables in single line
a = 5
b = 10
a, b = a, b
print "Swapped values of a and b are", a, b
Output
Swapped values of a and b are 10 5
Explanation:
Python evaluates expressions from left to right.But while evaluating an assignment, the right-hand side is evaluated before the left-hand side.
The expression a,b = b,a in third line can be evaluated as follows:
1) The right-hand side b,a is evaluated, i.e a tuple of two elements is created in the memory. The two elements are the objects identified by the identifiers b and a.
2) The creation of the tuple is done, but no assignement of this tuple object is made, but that is not the concern issue as python know where the tuple is internally.
3) The left-hand side is evaluated, i.e the tuple which is stored in memory is assigned to the left-hand side
as the left-hand side is composed of two identifiers a and b, the tuple is unpacked in order that the first identifier a is assigned by the first element of the tuple (i.e b)and the second identifier b is assigned by the second element of the tuple (i.e a)
In simple words, for python program in third line the expression is evaluated as: First right gets assigned to first left, second right gets assigned to second left, at the same time therefore swapping values of a and b.
0 Comment(s)