Master Python’s enumerate(): Loop with Indexes Made Simple
This guide explains Python’s built‑in enumerate() function, covering its purpose, syntax, parameters, return type, and practical examples with lists, tuples, strings, dictionaries and sets to help you iterate with automatic indexing in for‑loops.
What is enumerate() ?
The enumerate() function turns any iterable object—such as a list, tuple, string, dictionary, or set—into an iterator that yields pairs consisting of a running index and the corresponding item, which is especially handy inside for loops.
Syntax
enumerate(sequence, start=0)Parameters sequence – a sequence, iterator, or any object that supports iteration. start – the index from which counting begins (default is 0).
Return value
The function returns an enumerate object, which is an iterator that produces (index, value) tuples.
Practical examples
Iterating over a list
for i in enumerate([1, 2, 3, 4, 5]):
print(i)
# Output:
# (0, 1)
# (1, 2)
# (2, 3)
# (3, 4)
# (4, 5)Iterating over a tuple
for i in enumerate((1, 2, 3)):
print(i)
# Output:
# (0, 1)
# (1, 2)
# (2, 3)Iterating over a string
for i in enumerate('help'):
print(i)
# Output:
# (0, 'h')
# (1, 'e')
# (2, 'l')
# (3, 'p')Iterating over a dictionary (keys only)
for i in enumerate({'name': 'zoe', 'age': 18}):
print(i)
# Output (order may vary):
# (0, 'name')
# (1, 'age')Iterating over a set
for i in enumerate({12, 3}):
print(i)
# Output (order may vary):
# (0, 3)
# (1, 12)These examples demonstrate how enumerate() can be used with various iterable types to obtain both the element and its position without manually managing a counter.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
