🐍 10 Python Tricks That Can Instantly Improve Your Code

Vo1d_sVo1d_s
2 min read

Here are 10 Python tips that can improve the logic and readability of your code — whether you're just starting out or already writing scripts. These are beginner-friendly, but even advanced developers might find something new.

Let’s dive in. 👇


1. Use enumerate() Instead of Manual Indexing

When you need both the index and the value from a list, enumerate() is a cleaner alternative to using range(len(...)).

Don’t do this:

for i in range(len(items)):
    print(i, items[i])

Do this instead:

for i, item in enumerate(items):
    print(i, item)

It’s cleaner, easier to read, and avoids common indexing bugs.


2. Use with open() to Handle Files Safely

Using with ensures that the file is properly closed, even if an error occurs.

Don’t do this:

f = open("file.txt")
data = f.read()
f.close()

Do this instead:

with open("file.txt") as f:
    data = f.read()

Much neater — and you don’t have to remember to call close().


3. Write Compact List Comprehensions

List comprehensions let you create new lists in a single, readable line.

Long version:

squares = []
for num in range(10):
    squares.append(num**2)

Better version:

squares = [num**2 for num in range(10)]

It’s more compact, and in many cases, easier to understand at a glance.


4. Use dict.get() to Avoid Key Errors

Want to retrieve a value from a dictionary, but avoid crashes if the key doesn't exist? Use .get() with a fallback value.

data = {"name": "John", "age": 37}

# Key exists
name = data.get("name", "Unknown")
print(name)  # Output: John

# Key does not exist
job = data.get("job", "Unknown")
print(job)   # Output: Unknown

This is much safer than directly accessing the key with data["job"].


5. Unpack Multiple Values Easily

You can assign multiple variables in one line using unpacking.

name, age, job = "John", 37, "Coder"
print(name)  # Output: John
print(age)   # Output: 37
print(job)   # Output: Coder

This also works with functions that return multiple values:

def get_info():
    return "Alice", 29

name, age = get_info()
print(name)  # Output: Alice
print(age)   # Output: 29

Simple and elegant.

0
Subscribe to my newsletter

Read articles from Vo1d_s directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vo1d_s
Vo1d_s