How to Count Items with Default Parameters in Python
Define a Python function that prints each item with a running counter, using default parameters to allow custom start values and step increments.
Python code
13 linesdef count_items(items, start=0, step=1):
"""Count items in a list with configurable start value and step."""
count = start
for item in items:
print(f"{count}: {item}")
count += step
if __name__ == "__main__":
fruits = ["apple", "banana", "cherry"]
print("Default parameters (start=0, step=1):")
count_items(fruits)
print("\nCustom parameters (start=10, step=2):")
count_items(fruits, start=10, step=2)
Output
Default parameters (start=0, step=1):
0: apple
1: banana
2: cherry
Custom parameters (start=10, step=2):
10: apple
12: banana
14: cherry
How it works
The count_items function uses default parameter values (start=0, step=1), making them optional when calling the function. Inside the loop, count starts at the given start value and increments by step after each iteration, printing a formatted string with the current count and item. This pattern is useful for generating sequences or numbered lists without manually tracking the index. The if __name__ == '__main__' guard ensures the demo runs only when the script is executed directly, not when imported.
Common mistakes
- Forgetting to include `start` and `step` in the function signature, making them mandatory.
- Using mutable objects (like lists) as default parameter values, which persist across calls.
- Assuming the function returns the count instead of printing it — it returns `None`.
- Incrementing `count` before printing, which shifts the displayed numbers.
Variations
- Return a list of formatted strings instead of printing them directly.
- Use `enumerate(items, start=start)` with a custom step via multiplication.
Real-world use cases
- Displaying numbered task lists in CLI tools, starting from 1 or custom offsets.
- Logging events with a monotonic sequence number that increments by a custom step (e.g., 10).
- Generating labeled footer or header lines in reports with adjustable numbering.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.