Here are 20 Python programming tricks that can help you write more Pythonic, efficient, and readable code:
1. List Comprehensions
Create lists in a concise and readable way.
squares = [x**2 for x in range(10)] even_squares = [x**2 for x in range(10) if x % 2 == 0] print(squares) print(even_squares)
Concise list creation.
2. Dictionary Comprehensions
Similar to list comprehensions, but for dictionaries.
square_map = {x: x**2 for x in range(5)} even_square_map = {x: x**2 for x in range(10) if x % 2 == 0} print(square_map) print(even_square_map)
Concise dictionary creation.
3. Set Comprehensions
For creating sets concisely.
squares_set = {x**2 for x in range(10)} even_squares_set = {x**2 for x in range(10) if x % 2 == 0} print(squares_set) print(even_squares_set)
Concise set creation.
4. The Walrus Operator (Python 3.8+)
Assign values to variables as part of an expression.
if (n := len("hello world")) > 10: print(f"Length is {n}, which is greater than 10")
Inline assignment within expressions.
5. Enumerate for Index and Value
Iterate through a sequence while keeping track of the index.
my_list = ['a', 'b', 'c'] for index, value in enumerate(my_list): print(f"Index: {index}, Value: {value}")
Efficiently accessing index and value.
6. Zip for Parallel Iteration
Iterate over multiple iterables in parallel.
names = ['Alice', 'Bob', 'Charlie'] ages = [30, 25, 35] for name, age in zip(names, ages): print(f"{name} is {age} years old.")
Iterating through multiple lists simultaneously.
7. Unpacking Iterables
Easily assign elements of an iterable to variables. (See * in assignments for extended unpacking)
point = (1, 2, 3) x, y, z = point print(f"x: {x}, y: {y}, z: {z}") head, *tail = [1, 2, 3, 4, 5] print(f"Head: {head}, Tail: {tail}")
Conveniently assigning iterable elements.
8. The Asterisk (*) for Function Arguments
Use *args
for variable positional arguments and **kwargs
for variable keyword arguments. (See Keyword-Only Arguments and Argument Unpacking)
def sum_all(*args): total = 0 for num in args: total += num return total print(sum_all(1, 2, 3, 4)) def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") print_info(name="Alice", age=30)
Flexible function argument handling.
9. Using else
with for
and while
Loops
The else
block executes if the loop completes normally (not broken).
for i in range(5): if i == 10: break else: print("Loop completed without a break.")
Executing code after normal loop completion.
10. The collections
Module
Provides specialized container datatypes like Counter
, defaultdict
, deque
, etc.
from collections import Counter, defaultdict counts = Counter(['a', 'b', 'a', 'c', 'b', 'a']) print(counts) my_dict = defaultdict(int) my_dict['a'] += 1 my_dict['b'] += 2 print(my_dict)
Using specialized container types.
11. Slicing Lists and Strings
Powerful way to extract portions of sequences. (See List Slicing and Sequence Types)
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(my_list[2:5]) # [2, 3, 4] print(my_list[:3]) # [0, 1, 2] print(my_list[7:]) # [7, 8, 9] print(my_list[::2]) # [0, 2, 4, 6, 8] print(my_list[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Efficiently extracting subsequences.
12. Ternary Conditional Operator
Write concise single-line conditional expressions. (See Conditional Expressions)
age = 20 status = "adult" if age >= 18 else "minor" print(status)
Writing concise conditional assignments.
13. Using any()
and all()
Check if any or all elements in an iterable satisfy a condition.
numbers = [1, 2, 3, 0, 5] has_zero = any(x == 0 for x in numbers) all_positive = all(x > 0 for x in numbers) print(f"Has zero: {has_zero}") print(f"All positive: {all_positive}")
Conveniently checking iterable conditions.
14. F-strings (Formatted String Literals)
A clean and readable way to embed expressions inside string literals (Python 3.6+).
name = "Bob" age = 27 print(f"My name is {name} and I am {age} years old.")
Readable string formatting.
15. The map()
and filter()
Functions
Apply a function to all items in an iterable or filter items based on a condition.
numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, numbers)) evens = list(filter(lambda x: x % 2 == 0, numbers)) print(f"Squared: {squared}") print(f"Evens: {evens}")
Functional programming tools for iterables.
16. Using itertools
for Efficient Iteration
Provides functions for creating efficient iterators for various purposes (e.g., combinations, permutations, infinite iterators).
from itertools import combinations, permutations letters = ['a', 'b', 'c'] print(list(combinations(letters, 2))) print(list(permutations(letters)))
Powerful tools for creating iterators.
17. The functools
Module
Provides higher-order functions and operations on callable objects (e.g., partial
, lru_cache
).
from functools import partial, lru_cache def multiply(x, y): return x * y double = partial(multiply, 2) print(double(5)) @lru_cache(maxsize=None) def fibonacci(n): if n <= 1: return n return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(10))
Useful tools for working with functions.
18. Swapping Variables
A Pythonic way to swap the values of two variables without a temporary variable.
a = 10 b = 20 a, b = b, a print(f"a: {a}, b: {b}")
Concise variable swapping.
19. Context Managers (with
statement)
Ensure that resources are properly managed (e.g., files are closed, connections are released).
with open("my_file.txt", "w") as f: f.write("Hello, world!")
Ensuring proper resource management.
20. Using help()
and dir()
for Exploration
Built-in functions to get documentation and list attributes of objects.
help(list) my_list = [1, 2, 3] print(dir(my_list))
Tools for understanding Python objects and modules.
Leave a Reply