1.enumerate
enumerate(iterable) wraps any iterable in a lazy sequence of (index, item) pairs, starting at 0 by default. It replaces the manual counter loop with one built into the language.
Key features
- enumerate(iterable) yields (index, item) tuples, lazily, one at a time
- Indexing starts at 0 by default — pass start=N to begin anywhere else
- Unpack directly in a for loop: for i, item in enumerate(seq)
- Works on any iterable, not just lists — strings, dicts, generators too
- list(enumerate(seq)) materializes every pair if a real list is needed
enumerate over ["a", "b", "c"]
- an iterable — ["a", "b", "c"]
- enumerate() pairs each item — with a running index, lazily
- (index, item) tuples — (0, 'a'), (1, 'b'), (2, 'c')
Command
for index, item in enumerate(sequence): # index starts at 0
...
for index, item in enumerate(sequence, start=1): # index starts at 1
...enumerate(iterable, start=0) yields lazy (index, item) pairs — unpack them directly in a for loop instead of maintaining a manual counter.