Python Swap Two Variables with and without Temporary Variable

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))

Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.