Python Swap Two Variables with and without Temporary Variable

avatar
Published: Nov 30, 2022

In this snippet, we will learn how to swap two variables with and without a temporary variable.

With Temporary Variable

a = 10
b = 15

# temporary variable and swap the values
temp = a
a = b
b = temp

print('The value of a after swapping: {}'.format(a))
print('The value of b after swapping: {}'.format(b))

Without Temporary Variable

a = 5
b = 10

a, b = b, a

print('The value of a after swapping: {}'.format(a))
print('The value of b after swapping: {}'.format(b))