Python Swap Variables | Multiple Methods with Examples

Python Swap Variables

Swapping variables means exchanging the values of two variables. Python provides several ways to swap variables easily.

Variables की values को एक-दूसरे से बदलना Swap करना कहलाता है। Python में इसे करने के कई आसान तरीके हैं।

Method 1: Using a Temporary Variable
a = 5
b = 10
print('Before swap: a =', a, ', b =', b)
temp = a
a = b
b = temp
print('After swap: a =', a, ', b =', b)

This method uses a temporary variable to hold a value during swapping.

यह तरीका एक temporary variable का उपयोग करता है।

Sample Output:

Before swap: a = 5 , b = 10
After swap: a = 10 , b = 5
Method 2: Pythonic Way - Tuple Unpacking
a = 5
b = 10
print('Before swap: a =', a, ', b =', b)
a, b = b, a
print('After swap: a =', a, ', b =', b)

Python allows swapping variables directly without a temp variable using tuple unpacking.

Python में temp variable के बिना tuple unpacking से swap किया जाता है।

Sample Output:

Before swap: a = 5 , b = 10
After swap: a = 10 , b = 5
Method 3: Arithmetic Operations
a = 5
b = 10
print('Before swap: a =', a, ', b =', b)
a = a + b
b = a - b
a = a - b
print('After swap: a =', a, ', b =', b)

Swap variables using arithmetic operations without temp variable.

Arithmetic ऑपरेशन का उपयोग करके temp variable के बिना swap करें।

Sample Output:

Before swap: a = 5 , b = 10
After swap: a = 10 , b = 5
Method 4: XOR Bitwise Operation
a = 5
b = 10
print('Before swap: a =', a, ', b =', b)
a = a ^ b
b = a ^ b
a = a ^ b
print('After swap: a =', a, ', b =', b)

Use XOR bitwise operator to swap variables without temp variable.

XOR bitwise ऑपरेटर का उपयोग करके temp variable के बिना swap करें।

Sample Output:

Before swap: a = 5 , b = 10
After swap: a = 10 , b = 5
Method 5: Swapping Variables with User Input
a = input('Enter first value: ')
b = input('Enter second value: ')
print('Before swap: a =', a, ', b =', b)
a, b = b, a
print('After swap: a =', a, ', b =', b)

Swap two variables by reading values from the keyboard using tuple unpacking.

Keyboard से input लेकर tuple unpacking से swap करें।

Sample Output:

Enter first value: 7
Enter second value: 9
Before swap: a = 7 , b = 9
After swap: a = 9 , b = 7