ActiveState Code

Recipe 65112: Swapping values without using a temporary variable


You want to swap the values of some variables, but don't want to use a temporary variable.

Python
1
a, b, c = b, c, a

Discussion

Most programming languages oblige you to use a temporary intermediate variable when swapping the values of variables:

temp = a a = b b = c c = temp

But Python lets you make use of tuple packing and unpacking to do a direct assignment:

a, b, c = b, c, a

Comments

  1. 1. At 2:13 p.m. on 8 mar 2004, Christopher Dunn said:

    Runtime penalty. This is great for basic coding, but for inner loops use the temporary variable.

    This comes straight from the Python Tutorial, section 10.10 on Performance Measurement.

    >>> from timeit import Timer
    >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
    0.60864915603680925
    >>> Timer('a,b = b,a', 'a=1; b=2').timeit()
    0.8625194857439773
    

    http://www.python.org/doc/2.3.3/tut/node12.html

  2. 2. At 12:04 a.m. on 29 mar 2007, Ravi Kshirsagar said:

    I found tuple method is faster. don't know the reason but this is what I got on my system

    >>> from timeit import Timer
    
    
    
    >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
    

    0.25679183006286621

    >>> Timer('a,b = b,a', 'a=1; b=2').timeit()
    

    0.20631599426269531

    so bye to temp variables

Sign in to comment