Sobes.tech
Intern

How to swap the values of two variables?

sobes.tech AI

Answer from AI

Using tuple unpacking:

# Initial values
a = 5
b = 10

# Swap the values of a and b
a, b = b, a

# Now a = 10, b = 5
print(f"a = {a}, b = {b}")

Using a temporary variable:

# Initial values
a = 5
b = 10

# Save the value of a in a temporary variable
temp = a

# Assign the value of b to a
a = b

# Assign the value from the temporary variable to b
b = temp

# Now a = 10, b = 5
print(f"a = {a}, b = {b}")