Inverting two variables without using a temporary

Asked

Viewed 214 times

8

How can I reverse the value of a for b and b for a without using another variable? For example, a worthwhile 1 becomes real b worthwhile 3 and b becomes real a that was worth 1.

#antes de inverter
a = 1
b = 3

#depois de inverter
a = 3
b = 1

2 answers

9

Try Multiple Assignment

a=1
b=3

print("a=",a, "b=", b) 
a,b = b,a #Invertendo as variáveis sem uma variável auxiliar
print("a=",a, "b=", b)

Example above is very basic but functional for what you want.

  • 2

    I opened the question Multiple assignment in Python uses tuples? to discuss the internal workings behind this multiple assignment.

  • 1

    This does what I want, but if I’m not mistaken the tuple that will be unpacked will create a new variable

  • 1

    @Nium Does exactly what you need, has more details on the link of the first comment.

8


For practical purposes, prefer multiple assignment, cited in this answer.

Out of curiosity:

When variables are integer, you can also invert with mathematical addition and subtraction operations:

>>> a = 1
>>> b = 3

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

>>> print('a =', a, 'b =', b)
a = 3 b = 1

Or using the XOR operator:

>>> a = 1
>>> b = 3

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

>>> print('a =', a, 'b =', b)
a = 3 b = 1
  • That’s a nice answer, Anderson! I hadn’t even thought of these ways, but for performance purposes, it would have some difference between addition and subtraction; XOR operation; or dynamic assignment or it would just be several ways to do the same operation?

  • @Luizaugusto Overall, this would be micro-optimization and, especially in Python, we wouldn’t have to worry about it, but yes, there are differences. From what I’ve analyzed now, multiple attribution tends to be the most efficient, but they were shallow tests that we couldn’t blindly trust.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.