TGViewer
Learn Python Coding Learn Python Coding @pythonre · 40.9K subscribers
Post #8663 784
💡 Top 10 More Python Clean Code Practices

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
More from @pythonre
  1. Oct 17, 2026😰 15-Hour "Python for Data Science" Course ⚡️ Learn Python for Data Science https://enghu…
  2. Oct 13, 2026https://substack.com/@husseinsheikho?utm_source=share&utm_medium=android&r=3hwnr8 Follow m…
  3. Oct 10, 2026📚 Download 10 Python books for FREE: 1. Think Python — O’Reilly https://t.co/X7y3pX68IW 2…
  4. Oct 7, 2026Python Lists: A Quick Reference 🐍 * Definition: Lists are ordered, mutable collections th…
  5. Oct 7, 2026📱 270 tools for Python developers The repository contains: 🫡 Linters and formatters; 🫡…
  6. Oct 7, 2026Hands On Python Data Science - Data Science Bootcamp Master Python for Data Science with R…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →