Python is famous for its readability and expressiveness. But many developers — even experienced ones — write Python like it's Java or C#, missing the elegant tricks the language was built for. Here are 10 one-liners that will change how you think about Python.
1. List Comprehension Instead of a For Loop
The most fundamental Python trick. Replace verbose for-loops with a single readable line:
# Instead of this:
squares = []
for n in range(10):
squares.append(n ** 2)
# Write this:
squares = [n ** 2 for n in range(10)]
# With a filter:
even_squares = [n ** 2 for n in range(10) if n % 2 == 0]
2. Swap Two Variables Without a Temp
a, b = 5, 10
a, b = b, a # a=10, b=5
This uses Python's tuple unpacking. It's not just shorter — it's also slightly faster than using a temporary variable.
3. Flatten a Nested List
nested = [[1, 2], [3, 4], [5, 6]]
flat = [x for row in nested for x in row]
# [1, 2, 3, 4, 5, 6]
4. The Walrus Operator (:=) for Assign-and-Test
New in Python 3.8, the walrus operator lets you assign a value and test it in the same expression:
# Read lines until we find one longer than 100 chars
while (line := file.readline()) and len(line) <= 100:
process(line)
# Filter a list while computing a value once
results = [y for x in data if (y := transform(x)) > 0]
5. Dictionary Comprehension
# Map names to their lengths
names = ["Alice", "Bob", "Charlie"]
name_lengths = {name: len(name) for name in names}
# {'Alice': 5, 'Bob': 3, 'Charlie': 7}
# Invert a dictionary (swap keys and values)
inverted = {v: k for k, v in original.items()}
6. enumerate() — Never Use range(len()) Again
# Bad:
for i in range(len(items)):
print(i, items[i])
# Good:
for i, item in enumerate(items, start=1):
print(i, item)
7. zip() for Parallel Iteration
names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# Unzip (transpose) a list of tuples
pairs = [(1, "a"), (2, "b"), (3, "c")]
numbers, letters = zip(*pairs)
8. any() and all() for Readable Condition Checks
scores = [78, 92, 85, 61]
# Did anyone fail? (below 70)
has_fail = any(s < 70 for s in scores) # True
# Did everyone pass?
all_pass = all(s >= 70 for s in scores) # False
9. sorted() with a Key Function
people = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Eve", "age": 35},
]
# Sort by age, youngest first
youngest_first = sorted(people, key=lambda p: p["age"])
# Sort strings case-insensitively
names_sorted = sorted(names, key=str.lower)
10. Ternary Expression (Inline If-Else)
# Instead of:
if score >= 60:
result = "pass"
else:
result = "fail"
# Write:
result = "pass" if score >= 60 else "fail"
# Works in list comprehensions too:
labels = ["pass" if s >= 60 else "fail" for s in scores]
Ready to Master Python?
Our 10-week Python coaching track takes you from basics to building real automation, APIs, and database-backed apps — with 1-on-1 sessions tailored to your pace.
View the Python Course →