Monday, April 4, 2016

One Liner swaping of variables using tuples

In Python, it is possible to create a one liner code to swap the value of
two variables, this is how
a = 2
b = 4
print "a = ",a,"b = ",b

# One liner swap of variable using tuples

(a, b) = (b, a)
print "a = ",a,"b = ",b

# To improve the readability 
# you can write the tuple 
# without parenthesis, as
a, b = b, a

No comments:

Post a Comment