DEV Community

Cover image for Simplify Your Python Code with Clean Code Best Practices
Halcolo
Halcolo

Posted on

Simplify Your Python Code with Clean Code Best Practices

When writing code, there are often many ways to do the same thing—but some ways are cleaner, simpler, and easier to understand than others. In this post, I’ll show you simple tips to write cleaner Python code, following some key clean code principles. The goal? Write Python that's easier to read, maintain, and reuse.

Let's dive in! 👇

✅ Use Ternary Operators

A ternary operator is a compact way to write if-else statements in a single line. This can be useful for simple decisions like checking if someone is an adult.

Instead of:


def is_adult(age):
    if age > 18:
        return True
    else:
        return False
Enter fullscreen mode Exit fullscreen mode

You can write:


def is_adult(age):
    return True if age > 18 else False

Enter fullscreen mode Exit fullscreen mode

But there's more! Since age > 18 already returns a Boolean (True or False), you can simplify it even further:


def is_adult(age):
    return age > 18
Enter fullscreen mode Exit fullscreen mode

That’s clean, readable, and Pythonic! ✅

🔁 Use List Comprehensions Instead of Loops

List comprehensions are a cleaner way to create lists without using verbose loops.

Instead of:


squares = []
for i in range(10):
    squares.append(i * i)
Enter fullscreen mode Exit fullscreen mode

Use:


squares = [i * i for i in range(10)]
Its shorter, more readable, and avoids unnecessary lines.
Enter fullscreen mode Exit fullscreen mode

❓ Use Meaningful Function and Variable Names

Your code should be self-explanatory. Avoid vague names like x, do_thing, or data1.

Bad:


def d(a):
    return a > 18
Enter fullscreen mode Exit fullscreen mode

Good:


def is_adult(age):
    return age > 18
Enter fullscreen mode Exit fullscreen mode

Meaningful names improve understanding without needing extra comments.

🙅‍♂️ Avoid Unnecessary else After return

If you return in an if, there's no need for an else.

Instead of:


def is_positive(n):
    if n > 0:
        return True
    else:
        return False
Enter fullscreen mode Exit fullscreen mode

Just write:


def is_positive(n):
    return n > 0
Enter fullscreen mode Exit fullscreen mode

Cleaner, right?

🧹 Remove Redundant return None

In Python, functions return None by default if there’s no return statement. Don’t write what’s already implicit.

Instead of:


def log_message(msg):
    print(msg)
    return None
Enter fullscreen mode Exit fullscreen mode

Use:


def log_message(msg):
    print(msg)

Enter fullscreen mode Exit fullscreen mode

📛 Use enumerate() Instead of Manual Indexing

Avoid using range(len(...)) when iterating through a list and needing the index.

Instead of:


for i in range(len(fruits)):
    print(i, fruits[i])
Enter fullscreen mode Exit fullscreen mode

Use:

for i, fruit in enumerate(fruits):
    print(i, fruit)
Enter fullscreen mode Exit fullscreen mode

✂️ Use join() Instead of Loops to Build Strings

Concatenating strings in a loop is inefficient and messy.

Instead of:


words = ['clean', 'code', 'rocks']
sentence = ''
for w in words:
    sentence += w + ' '
Enter fullscreen mode Exit fullscreen mode

Use:


sentence = ' '.join(words)
Enter fullscreen mode Exit fullscreen mode

⏪ Use Tuple Unpacking for Swapping Values

Swapping variables without a temp variable is a Python classic.

Instead of:


temp = a
a = b
b = temp
Enter fullscreen mode Exit fullscreen mode

Use:

a, b = b, a
Enter fullscreen mode Exit fullscreen mode

Shorter and instantly understandable.

📦 Bonus: Use Python's Built-in Functions

Python gives you powerful built-in tools. Don’t reinvent the wheel.

Example:


# Check if any number is negative
numbers = [1, 3, -2, 5]

if any(n < 0 for n in numbers):
    print("There's a negative number!")
Enter fullscreen mode Exit fullscreen mode

Functions like any(), all(), sum(), map(), and filter() can help you write more elegant code.

Final Thoughts

Clean code is not about writing fewer lines, it's about writing better lines. Python is already expressive, so lean into that by simplifying logic, naming things clearly, and using the language's powerful features.

Top comments (0)