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
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


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()
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()


Ravi Kshirsagar 17 years 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()


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


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