1. Use Ternary Operators for Simple Conditionals
(Replaces a multi-line
if/else block for simple assignments.)Cluttered Way:
is_adult = False
age = 20
if age >= 18:
is_adult = True
Clean Way:
age = 20
is_adult = True if age >= 18 else False
2. Use
str.join() for Concatenating Strings in a List(More efficient and readable than using
+ in a loop.)Cluttered Way:
words = ["hello", "world", "this", "is", "python"]
sentence = ""
for word in words:
sentence += word + " "
Clean Way:
words = ["hello", "world", "this", "is", "python"]
sentence = " ".join(words)
3. Use
collections.defaultdict for Grouping or Counting(Avoids manual key checking when appending to lists or incrementing counters.)
Cluttered Way:
data = [('fruit', 'apple'), ('veg', 'carrot'), ('fruit', 'banana')]
grouped = {}
for category, item in data:
if category not in grouped:
grouped[category] = []
grouped[category].append(item)Clean Way:
from collections import defaultdict
data = [('fruit', 'apple'), ('veg', 'carrot'), ('fruit', 'banana')]
grouped = defaultdict(list)
for category, item in data:
grouped[category].append(item)
4. Use
collections.namedtuple for Simple Data Objects(Provides readable attribute access instead of relying on numeric indices.)
Cluttered Way:
point = (10, 20)
# Unclear what point[0] or point[1] represents
if point[0] > 5:
print("X is greater than 5")
Clean Way:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
point = Point(10, 20)
if point.x > 5:
print("X is greater than 5")
5. Use Argument Unpacking (
* and **)(Passes all items from a list or dictionary as arguments to a function.)
Cluttered Way:
def print_coords(x, y, z):
print(f"X: {x}, Y: {y}, Z: {z}")
coords = [1, 2, 3]
print_coords(coords[0], coords[1], coords[2])
Clean Way:
def print_coords(x, y, z):
print(f"X: {x}, Y: {y}, Z: {z}")
coords_list = [1, 2, 3]
print_coords(*coords_list)
coords_dict = {'x': 4, 'y': 5, 'z': 6}
print_coords(**coords_dict)
6. Use
any() and all() for Boolean Checks on Iterables(More declarative and concise than manual loops with a flag variable.)
Cluttered Way:
numbers = [-1, -2, 5, -4]
has_positive = False
for num in numbers:
if num > 0:
has_positive = True
break
Clean Way:
numbers = [-1, -2, 5, -4]
has_positive = any(num > 0 for num in numbers)
7. Prefer Generator Expressions for Large Datasets
(They don't store the entire sequence in memory, making them highly efficient.)
Cluttered Way (can cause high memory usage):
total = sum([i * i for i in range(1000000)])
Clean Way (memory efficient):
total = sum(i * i for i in range(1000000))
8. Use Destructuring for More Powerful Unpacking
(A clean way to assign elements from a sequence to multiple variables.)
Cluttered Way:
numbers = [1, 2, 3, 4, 5]
first = numbers[0]
last = numbers[-1]
Clean Way:
numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
# first = 1, middle = [2, 3, 4], last = 5