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


