Pythonic way of swapping values between two variables in Python
Run the code here: https://repl.it/@VinitKhandelwal/pythonic-swap
y = 2
x = 2
y = 1
a = 10
b = 20
a = 20
b = 10
Run the code here: https://repl.it/@VinitKhandelwal/pythonic-swap
x = 1
y = 2
print(f"x = {x}")
print(f"y = {y}")
# Swap x and y using traditional coding practice
temp = x
x = y
y = temp
print(f"x = {x}")
print(f"y = {y}")
a = 10
b =20
print(f"a = {a}")
print(f"b = {b}")
# Swap a and b using Pythonic coding practice
a, b = b, a
print(f"a = {a}")
print(f"b = {b}")
OUTPUT
x = 1y = 2
x = 2
y = 1
a = 10
b = 20
a = 20
b = 10
Comments
Post a Comment