Swapping Values In Python

When swapping values in python there really is not reason to use a temporary variable. We can take advantage of tuples to initiate the swap, which allows us to do the swap without a temporary variable.

 

Below is an example of non-idiomatic swapping.

a = ‘A’
b = ‘B’
temp = a
a = b
b = temp

 

Below is an example of utilizing the power of a Python tuple.

a = ‘A’
b = ‘B’
(a, b) = (b, a)

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *