Search code examples
pythonpython-3.xpython-2.7variablesswap

Swap two numeric variables without unpacking in python


How can I swap two numeric variables without unpacking or define a new variable in python? I mean not this way:

a, b = b, a

and not this way:

c = a
a = b
b = c

Solution

  • You can do it this way:

    a = a + b
    b = a - b
    a = a - b