enumerate(sequence, start=0)
Generates counter-element pairs for elements in sequence. You can set the initial counter value with start. Use this function when you need a counter for elements in a sequence. It removes the need to manually initialize and update a separate counter variable.
Parameters
The enumerate() function accepts two parameters:
iterable— a sequence, iterator, or object that supports iteration.start(optional) — counting starts from this number. If omitted, counting begins from 0.
Return Value
enumerate()adds a counter to an iterable and returns an enumerated object.- Convert enumerated objects to a list or tuple using
list()ortuple().
Examples
sequence = [1, 2, 7, 19]
# Using a manual counter
idx = 0
for item in sequence:
print(idx)
idx += 1
# Using enumerate
for idx, item in enumerate(sequence):
print(idx)