Python Beginners Clean Code Tips

Python Tips Every Beginner Wishes They Knew Earlier

Small habits and built-in features that make your Python cleaner, faster, and more Pythonic

Sanskruti Varade · Python · ~6 min read

When I started learning Python, I wrote code that worked — but looked nothing like what experienced developers wrote. Same logic, same output, but theirs was half the length and twice as readable.

The gap wasn't intelligence. It was familiarity with the language's built-in features and idioms. These are the tips I wish someone had handed me on day one.

1. Use List Comprehensions Instead of Loops

# The long way
squares = []
for n in range(10):
    squares.append(n ** 2)

# The Pythonic way
squares = [n ** 2 for n in range(10)]

# With condition
even_squares = [n ** 2 for n in range(10) if n % 2 == 0]

Rule of thumb: if you're creating a new list by transforming or filtering another, a list comprehension is almost always cleaner.

2. Unpack Variables Instead of Indexing

# Don't do this
point = (10, 20)
x = point[0]
y = point[1]

# Do this
x, y = point

# Extended unpacking
first, *rest = [1, 2, 3, 4, 5]
# first = 1, rest = [2, 3, 4, 5]

3. Use enumerate When You Need Index + Value

# Don't do this
for i in range(len(items)):
    print(i, items[i])

# Do this
for i, item in enumerate(items):
    print(i, item)

4. Use zip to Iterate Over Multiple Lists

# Don't do this
for i in range(len(names)):
    print(names[i], scores[i])

# Do this
for name, score in zip(names, scores):
    print(name, score)

5. Use F-Strings for String Formatting

# Old ways
print("Hello, %s. You are %d." % (name, age))
print("Hello, {}. You are {}.".format(name, age))

# F-strings (Python 3.6+) — cleanest
print(f"Hello, {name}. You are {age}.")
print(f"Result: {2 ** 10}")        # Result: 1024
print(f"Name: {name.upper()}")

6. Use defaultdict and Counter from collections

# Word counting the hard way
word_count = {}
for word in words:
    if word not in word_count:
        word_count[word] = 0
    word_count[word] += 1

# Word counting with Counter
from collections import Counter
word_count = Counter(words)

# Grouping with defaultdict
from collections import defaultdict
groups = defaultdict(list)
for item in items:
    groups[item.category].append(item)

7. Use _ for Values You Don't Need

# Ignoring the second value
name, _ = ("Nidhi", 22)

# Looping n times without using the index
for _ in range(5):
    print("hello")

8. Use any() and all() Instead of Manual Loops

# Manual loop
found = False
for item in items:
    if item > 10:
        found = True
        break

# Pythonic
found = any(item > 10 for item in items)
all_valid = all(item > 0 for item in items)

9. Avoid Mutable Default Arguments

# WRONG — list is shared across all calls
def add_item(item, items=[]):
    items.append(item)
    return items

# CORRECT
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

Default arguments are evaluated once at function definition, not at each call. Mutable defaults persist across calls — use None as the default instead.

10. Use Context Managers for File Handling

# Don't do this — easy to forget close()
f = open("file.txt", "r")
data = f.read()
f.close()

# Always do this
with open("file.txt", "r") as f:
    data = f.read()
# File closes automatically, even if an exception occurs

The Bigger Picture

These tips share a common thread: Python is designed to be expressive. When something feels unnecessarily verbose or repetitive, there's usually a built-in that handles it better. The habit to build is asking "does Python already have something for this?" before writing it yourself.

The answer, more often than not, is yes.

← Back to Blog