1. Use List Comprehensions
List comprehensions are more concise and faster than traditional loops for creating lists.
numbers = [x * x for x in range(10) if x % 2 == 0]
2. Use Enumerate Instead of Range
Use enumerate()
to get index and value while iterating over a list.
for index, value in enumerate(['a', 'b', 'c']):
print(index, value)
3. Use F-Strings for String Formatting
F-strings (Python 3.6+) are cleaner and faster than %
or format()
.
name = "Alice"
print(f"Hello, {name}!")
4. Use Defaultdict and Counter
collections.defaultdict
and collections.Counter
simplify many tasks.
from collections import defaultdict, Counter
words = ['apple', 'banana', 'apple']
count = Counter(words)
print(count)
5. Unpack Multiple Variables
Python allows tuple unpacking to swap variables or extract multiple values.
a, b = b, a
6. Use Context Managers
Use with
to handle resources like files or database connections safely.
with open('file.txt') as f:
data = f.read()
7. Use Generators for Large Data
Generators use yield
to save memory when processing large datasets.
def gen_numbers():
for i in range(1000000):
yield i
8. Use Type Hints
Type hints improve code readability and help with IDE support and static analysis.
def add(a: int, b: int) -> int:
return a + b
9. Avoid Mutable Default Arguments
Using mutable defaults like lists in function args can lead to bugs.
def append_to_list(val, my_list=None):
if my_list is None:
my_list = []
my_list.append(val)
return my_list
10. Use Virtual Environments
Always isolate project dependencies using venv
or virtualenv
.
python -m venv venv
source venv/bin/activate
Conclusion: Mastering these tips will help you write cleaner, faster, and more reliable Python code. Happy coding!