Welcome, guest | Sign In | My Account | Store | Cart

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

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

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

5 comments

Christopher Dunn 20 years, 1 month ago  # | flag

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

Ravi Kshirsagar 17 years, 1 month ago  # | flag

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

swamy 11 years, 1 month ago  # | flag

a=5 b=6 print(a,b) a=a+b b=a-b a=a-b print(a,b)

x 10 years, 9 months ago  # | flag

a = a ^ b b = a ^ b a = a ^ b

David Sawyer 8 years, 10 months ago  # | flag

Python now optimizes out the temporary tuple construction and unpacking. So go ahead and use the short form a,b = b,a. Not sure what the XOR method has going for it... less readable, less performant, and only works if the values are both the same type and __xor__ is defined for that type.

Created by Hamish Lawson on Fri, 8 Jun 2001 (PSF)
Python recipes (4591)
Hamish Lawson's recipes (6)
Python Cookbook Edition 1 (103)

Required Modules

  • (none specified)

Other Information and Tasks