Swap Two Variables in One Line

331次阅读
没有评论

Welcome to the first day of your 365-day Python journey! Today, we’ll start with a simple yet elegant trick that showcases the beauty and power of Python’s syntax: swapping the values of two variables.

In many programming languages, to swap the values of two variables, you need a third, temporary variable. For example:

Python

# The traditional way
a = 5
b = 10
temp = a
a = b
b = temp
print(a)  # Output: 10
print(b)  # Output: 5

This method is perfectly fine and works, but Python provides a more concise and readable way to achieve the same result.

The Pythonic Way

In Python, you can swap two variables in a single line of code:

Python

a = 5
b = 10

# The Pythonic way
a, b = b, a

print(a)  # Output: 10
print(b)  # Output: 5

How does it work?

Python first evaluates the right side of the assignment (b, a), which creates a tuple of the values (10, 5). Then, it unpacks this tuple and assigns the values to the variables on the left side in order. So, a gets the first value 10, and b gets the second value 5.

This technique is not only shorter but also more intuitive once you get used to it. It’s a great example of writing “Pythonic” code—code that is clean, readable, and leverages the language’s features.

That’s it for Day 1! Try it out yourself and get a feel for this handy little trick. We’ll be back tomorrow with another useful Python tip.

正文完
 0
评论(没有评论)
验证码