liveBook · Manning

Enumerate

As explained in Python Workout, Second Edition

The enumerate function returns an iterator that yields pairs containing sequential indices and values from an iterable.

Use enumerate when a loop needs both each iterable item and its sequential index. It returns an iterator of two-element pairs, which tuple unpacking captures as separate variables. section 2.15

The practical pattern is:

  • Iterate directly over the result with for index, value in enumerate(iterable). section 2.15
  • Remember that counting starts at 0 unless a second argument supplies another starting index. section 8.31
  • Combine it with comprehensions when constructing indexed dictionaries or other derived collections. section 8.31

Print indexed characters

for index, one_letter in enumerate('abcd'): print(f'{index}: {one_letter}') To number letters from 1, use enumerate('abcd', 1). section 8.31

{char:index
 for index, char in enumerate(string.ascii_lowercase, 1)}

A compact dict comprehension pairs each lowercase letter with a one-based index. section 8.31

How Python Workout, Second Edition covers it

How deep it goes
Explains returned pairs, unpacking, default indexing, and custom starts; connects iterator behavior to broader protocol study.
Examples
Demonstrates indexed alphabet output, hexadecimal digit processing, and alphabet-to-number dictionary construction.
What it assumes
Assumes familiarity with for loops and iterable objects while reinforcing tuple unpacking and index-based processing.
What you can do after
Apply it via Python's built-in iterator to write concise loops and comprehensions that retain both positions and values.
How it connects
Connects enumerate with for loops, iterators, tuple unpacking, reversed, and dictionary comprehensions.

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 Workout, Second Edition. The section links point to the parts of the book it draws on.