Master 24 Essential Python Tricks to Write Cleaner, Faster Code
This comprehensive guide walks you through 24 powerful Python techniques—from list, dictionary, and set comprehensions to advanced modules like itertools, functools, and asyncio—showing concise syntax, practical examples, and best practices that help you write more efficient, readable, and maintainable code.
List Comprehensions
List comprehensions provide a concise syntax for constructing lists by iterating over an iterable and optionally applying a filter.
# Traditional loop
squares = []
for x in range(10):
squares.append(x ** 2)
# List comprehension
squares = [x ** 2 for x in range(10)]
print(squares)Dictionary Comprehensions
Dictionary comprehensions create dictionaries in a single expression, mapping keys to values while iterating.
# Traditional loop
squares_dict = {}
for x in range(10):
squares_dict[x] = x ** 2
# Dictionary comprehension
squares_dict = {x: x ** 2 for x in range(10)}
print(squares_dict)Set Comprehensions
Set comprehensions generate a set of unique elements using a similar syntax to list comprehensions.
# Set comprehension
unique_squares = {x ** 2 for x in range(10)}
print(unique_squares)Generator Expressions
Generator expressions produce a generator object that yields items lazily, saving memory for large sequences.
# Generator expression
squares_gen = (x ** 2 for x in range(10))
print(list(squares_gen)) # Convert to list to view contentsUnpacking
Unpacking assigns elements of an iterable to multiple variables in a single statement.
# Tuple unpacking
a, b = (1, 2)
print(a, b) # 1 2
# List unpacking with starred expression
numbers = [1, 2, 3]
first, *rest = numbers
print(first, rest) # 1 [2, 3]enumerate()
The enumerate function yields pairs of index and value while iterating over a sequence.
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")zip()
The zip function aggregates elements from multiple iterables into tuples, stopping at the shortest iterable.
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")Ternary Operator
A ternary expression offers a compact form of an if‑else statement.
x = 10
result = "Even" if x % 2 == 0 else "Odd"
print(result) # EvenContext Managers
Context managers guarantee that resources are released properly using the with statement.
# File handling
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# Custom context manager
class ManagedResource:
def __enter__(self):
print("Resource opened")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Resource closed")
with ManagedResource() as resource:
print("Using the resource")Decorators
Decorators wrap a function to modify or extend its behavior without changing its source code.
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()Classes and Inheritance
Object‑oriented programming in Python uses classes to encapsulate data and behavior; inheritance enables reuse and specialization.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclasses must implement this method")
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak())
print(cat.speak())Exception Handling
Use try/except/finally blocks to catch and handle runtime errors gracefully.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This always runs.")itertools and functools
The itertools module supplies fast iterator building blocks; functools provides higher‑order functions.
import itertools, functools
# itertools: combinations
numbers = [1, 2, 3]
print(list(itertools.combinations(numbers, 2))) # [(1, 2), (1, 3), (2, 3)]
# functools: reduce
def add(a, b):
return a + b
print(functools.reduce(add, [1, 2, 3, 4])) # 10collections Module
The collections module offers specialized container datatypes.
# namedtuple
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
pt = Point(1, 2)
print(pt.x, pt.y)
# deque (double‑ended queue)
from collections import deque
d = deque([1, 2, 3])
d.append(4)
d.appendleft(0)
print(d) # deque([0, 1, 2, 3, 4])
d.pop()
d.popleft()
print(d) # deque([1, 2, 3])
# Counter (multiset)
from collections import Counter
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
print(Counter(words))
# defaultdict (auto‑initialising dict)
from collections import defaultdict
dd = defaultdict(int)
for ch in 'ab':
dd[ch] += 1
print(dd)Advanced itertools
Common utilities include chain for concatenating iterables and groupby for grouping consecutive identical elements.
import itertools
# chain
combined = list(itertools.chain([1, 2, 3], [4, 5, 6]))
print(combined)
# groupby
items = ['A', 'B', 'B', 'C', 'A', 'A', 'B']
for key, group in itertools.groupby(items):
print(key, list(group))Advanced functools
partialfixes some arguments of a function, creating a new callable; lru_cache memoises function results.
from functools import partial, lru_cache
def multiply(x, y):
return x * y
double = partial(multiply, 2)
print(double(5)) # 10
@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10)) # 55contextlib Module
contextlib.contextmanagersimplifies creation of context managers using generator syntax.
from contextlib import contextmanager
@contextmanager
def managed_resource(name):
print(f"Resource {name} opened")
yield name
print(f"Resource {name} closed")
with managed_resource('example') as res:
print(f"Using {res}")logging Module
The logging module provides configurable log levels and formatting for debugging and monitoring.
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('Debug message')
logging.info('Info message')
logging.warning('Warning message')
logging.error('Error message')
logging.critical('Critical message')argparse Module
argparseparses command‑line arguments, automatically generating help messages.
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))unittest Module
Built‑in unittest offers a framework for writing and running test cases.
import unittest
class TestMathOperations(unittest.TestCase):
def test_addition(self):
self.assertEqual(1 + 1, 2)
def test_subtraction(self):
self.assertEqual(5 - 3, 2)
if __name__ == '__main__':
unittest.main()asyncio Module
asyncioenables asynchronous I/O using async / await syntax.
import asyncio
async def my_coroutine():
await asyncio.sleep(1)
print('Coroutine executed')
async def main():
task = asyncio.create_task(my_coroutine())
await task
asyncio.run(main())multiprocessing Module
The multiprocessing module spawns separate processes to leverage multiple CPU cores.
import multiprocessing
def worker(num):
print(f'Worker: {num}')
if __name__ == '__main__':
processes = []
for i in range(5):
p = multiprocessing.Process(target=worker, args=(i,))
processes.append(p)
p.start()
for p in processes:
p.join()pathlib Module
pathlibprovides an object‑oriented interface for filesystem paths.
from pathlib import Path
# Current directory
curr = Path('.')
print(curr)
# Create a new directory
new_dir = curr / 'new_folder'
new_dir.mkdir(exist_ok=True)
# List contents
for item in new_dir.iterdir():
print(item)dataclasses Module
dataclassesreduces boilerplate when defining classes that primarily store data.
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
p = Person(name='Alice', age=30)
print(p)Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
