liveBook · Manning

Enumerate

As explained in Python How-To

The enumerate function is a Python built-in function that returns an iterator producing position-and-item pairs from an iterable.

Need each loop iteration’s position alongside its item? Use enumerate instead of building a range from len(iterable). It produces a cleaner, more Pythonic loop. section 1.4.1 section 5.0

enumerate(iterable) creates an iterator that yields tuples of (counter, item). The counter starts at 0 by default; pass start=1 or another value to choose the first counter. Tuple unpacking assigns both values directly. section 5.3.1

Number tasks while iterating

tasks = ["Homework", "Laundry", "Museum"] for task_i, task in enumerate(tasks, start=1): print(f"Task {task_i}: {task}") # Task 1: Homework # Task 2: Laundry # Task 3: Museum section 5.3.1

Format structured task records

for task_i, task in enumerate(tasks, start=1): print(f"Task {task_i}: {task.title:<10}") print(f"{task.description:<18} {task.urgency}") This pattern combines enumeration, tuple unpacking, and formatted output while keeping the loop readable. section 5.3.1

Prefer enumerate when a loop needs both an item and its position:

  • Use enumerate(items) when zero-based counters are appropriate. section 5.3.1
  • Use enumerate(items, start=1) for human-facing numbering. section 5.3.1
  • Avoid manually combining range(len(items)), indexing, and counter arithmetic when enumerate expresses the intent directly. section 1.4.1 section 5.3.1

How Python How-To covers it

How deep it goes
Explains iterator creation, yielded tuples, default counters, start values, and tuple unpacking through worked loops.
Examples
Demonstrates numbered prime numbers and formatted task records using zero-based and one-based counters.
What it assumes
Assumes familiarity with for loops and iterables, while reinforcing tuple unpacking through the loop pattern.
What you can do after
Apply it via Python's built-in enumerate function to write readable position-aware loops.
How it connects
Connects enumerate with iterables, for loops, range, tuple unpacking, and f-strings.

Also explained in

Compare how 3 books explain enumerate →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.