Lists and Dictionaries of Functions in Python 2026 – Best Practices for Writing Functions
Since functions in Python are first-class objects, you can store them in lists, dictionaries, and other data structures. This powerful technique enables dynamic dispatch, plugin systems, strategy patterns, and clean command handling.
TL;DR — Key Takeaways 2026
- Store functions in lists for ordered execution or pipelines
- Use dictionaries of functions for dynamic lookup and command patterns
- This approach makes code more extensible and maintainable
- Combine with type hints for better clarity and safety
1. Lists of Functions (Pipeline Pattern)
def clean_text(text: str) -> str:
return text.strip().lower()
def remove_punctuation(text: str) -> str:
return ''.join(c for c in text if c.isalnum() or c.isspace())
def tokenize(text: str) -> list:
return text.split()
# List of processing functions (pipeline)
text_processors = [clean_text, remove_punctuation, tokenize]
def process_text(text: str):
for processor in text_processors:
if isinstance(text, str):
text = processor(text)
else:
text = processor(text) # for list output
return text
result = process_text("Hello, World! 123")
print(result) # ['hello', 'world', '123']
2. Dictionaries of Functions (Command / Strategy Pattern)
def add(a: int, b: int) -> int: return a + b
def subtract(a: int, b: int) -> int: return a - b
def multiply(a: int, b: int) -> int: return a * b
def divide(a: int, b: int) -> float:
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
# Dictionary mapping operation names to functions
operations = {
"add": add,
"subtract": subtract,
"multiply": multiply,
"divide": divide,
}
def calculate(operation: str, a: int, b: int):
if operation not in operations:
raise ValueError(f"Unknown operation: {operation}")
func = operations[operation]
return func(a, b)
print(calculate("add", 10, 5)) # 15
print(calculate("multiply", 10, 5)) # 50
3. Best Practices in 2026
- Use lists of functions for ordered processing pipelines
- Use dictionaries for command patterns and dynamic dispatch
- Store only callable objects and validate them
- Add type hints and clear documentation for each function
- Consider using enums or constants as keys for better safety
Conclusion
Storing functions in lists and dictionaries is a powerful Python idiom that leads to cleaner, more extensible, and maintainable code. In 2026, this technique is widely used for building plugin systems, command handlers, processing pipelines, and flexible APIs.
Next steps:
- Look for opportunities in your code to replace long if-elif chains with dictionaries of functions
- Related articles: Writing Functions in Python 2026 • Functions as Objects in Python 2026