Python Program to Swap Two Variables

Python Program to Swap Two Variables

Swapping two variables in Python can be done in a very elegant and concise manner without the need for a temporary variable. Here's how you can do it:

# Define two variables a = 5 b = 10 # Swap the variables a, b = b, a # Print the swapped values print("a =", a) print("b =", b) 

In the above code, the line a, b = b, a swaps the values of a and b:

  1. The right-hand side creates a tuple (b, a).
  2. The left-hand side unpacks the tuple, assigning the first value to a and the second value to b.

Thus, the values of a and b are swapped.


More Tags

mapi lifecycleexception angular-flex-layout compiler-warnings axon dependencies openfire android-mediaplayer kafka-consumer-api pid

More Programming Guides

Other Guides

More Programming Examples