python – Inverting two variables without using a temporary


How can I flip the value of a to b and b to a without using another variable? For example, a which is worth 1 becomes worth b which is worth 3 and b becomes worth a which was worth 1 .

#antes de inverter
a = 1
b = 3

#depois de inverter
a = 3
b = 1


Try Multiple Assignment


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 pretty basic but functional for what you want.

Scroll to Top