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.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 12 views 0 copies

Python code

13 lines
Python 3.9+
def 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

stdout
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

  1. Return a list of formatted strings instead of printing them directly.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.