Member-only story
20 Python Tricks Every Pro Should Know to Write Smarter Code
2 min readFeb 9, 2025
1. Swapping Variables Without a Temporary Variable
Instead of using a temporary variable for swapping:
a, b = 5, 10 a, b = b, a print(a, b)
2. Using List Comprehensions for Cleaner Code
Replace verbose loops with a one-liner:
squares = [x**2 for x in range(5)] print(squares)
3. The zip()
Function for Pairing Data
Easily combine two lists into pairs:
names = ["Alice", "Bob"]
ages = [25, 30]
combined = dict(zip(names, ages))
print(combined)
4. Using *
to Unpack
You can unpack lists, tuples, or ranges with *
:
numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
print(first, middle, last)
5. The Walrus Operator (:=
)
Introduced in Python 3.8, it allows assignment within expressions:
if (n := len("Python")) > 5:
print(f"String is long: {n}")
6. Dictionary Comprehensions
Quickly generate dictionaries:
squares = {x: x**2 for x in range(5)}
print(squares)