Saturday, December 24, 2016

Python how to swap two values in one line of code - tuple unpacking

 A common problem we need to solve is how to swap two values
 For example if we have to variables x and y, 
 we might want to swap the
 the values.  

 x = 123
 y = 456
 print('Start values:  a = {} b = {} '.format(x, y))

 temp = x
 x = y
 y = temp
 print('Finish values: a = {} b = {} '.format(x, y))


 A better, more succinct method is to use the cool 'tuple unpacking'

 x = 123
 y = 456
 print('Start values:  a = {} b = {} '.format(x, y))

 x, y = y, x
 print('Finish values: a = {} b = {} '.format(x, y))