Python is renowned for its simplicity and readability, but even seasoned developers can benefit from learning new tricks and best practices. Whether you're a beginner or an experienced programmer, these 10 tips will help you write cleaner, more efficient, and more Pythonic code.
List comprehensions provide a concise way to create lists. They’re often faster and more readable than traditional loops.
# Traditional loop
squares = []
for x in range(10):
squares.append(x**2)
# List comprehension
squares = [x**2 for x in range(10)]
Introduced in Python 3.6, f-strings are the most efficient and readable way to format strings.
name = "Alice"
age = 30
message = f"Hello, my name is {name} and I'm {age} years old."
When you need both the index and the value from a list, enumerate() is your friend.
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
Available from Python 3.8+, the walrus operator lets you assign and return a value in the same expression.
# Without walrus
n = len(data)
if n > 10:
print(f"List is too long ({n} elements)")
# With walrus
if (n := len(data)) > 10:
print(f"List is too long ({n} elements)")
Always use context managers (the with statement) when working with files or other resources to ensure they’re properly closed.
# Good
with open('file.txt', 'r') as f:
content = f.read()
# Avoid
f = open('file.txt', 'r')
content = f.read()
f.close()
Use the unpacking operator * to simplify assignments and function calls.
# Unpacking a list
first, *middle, last = [1, 2, 3, 4, 5]
print(first, middle, last) # 1 [2, 3, 4] 5
# Passing arguments
def add(a, b, c):
return a + b + c
nums = [1, 2, 3]
result = add(*nums)
Avoid KeyError exceptions and boilerplate code with defaultdict.
from collections import defaultdict
# Regular dict
counts = {}
for word in words:
if word not in counts:
counts[word] = 0
counts[word] += 1
# With defaultdict
counts = defaultdict(int)
for word in words:
counts[word] += 1
Use the key parameter in sorted() or list.sort() to define custom sorting logic.
students = [('Alice', 85), ('Bob', 75), ('Charlie', 90)]
# Sort by score (second element)
sorted_students = sorted(students, key=lambda x: x[1])
Use the timeit module to accurately measure the execution time of small code snippets.
import timeit
time = timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
print(time)
Improve code maintainability by documenting functions with docstrings and using type hints (introduced in Python 3.5+).
def greet(name: str) -> str:
"""Return a personalized greeting message."""
return f"Hello, {name}!"
These tips may seem simple, but mastering them will significantly improve your Python code’s quality, performance, and readability. Make them part of your daily coding habits!