enumerate (For Index, Element)
This page was last reviewed on Jun 7, 2023.
Dot Net Perls
Enumerate. In a collection, an element has both an index (where it is located) and a value (what it is). In a loop we often want both of these things.
With enumerate, we receive generated tuples containing an index and a value. Enumerate() is a built-in. It is often used in for-loops for iteration.
An initial example. This example uses a string list. Enumerate() acts on any iterable, even a tuple, but a list is a common target for it.
Info We can unpack the tuple directly in the for-loop clause. Or we can receive the tuple and access its items later.
animals = ["cat", "bird", "dog"] # Use enumerate to get indexes and elements from an iterable. # ... This unpacks a tuple. for i, element in enumerate(animals): print(i, element) # Does not unpack the tuple. for x in enumerate(animals): print(x, "UNPACKED =", x[0], x[1])
0 cat 1 bird 2 dog (0, 'cat') UNPACKED = 0 cat (1, 'bird') UNPACKED = 1 bird (2, 'dog') UNPACKED = 2 dog
String. In Python we use strings throughout many programs. With enumerate() we have a good way to loop over the characters in a string, while keeping track of indexes.
word = "one" # Enumerate over a string. # ... This is a good way to get indexes and chars from a string. for i, value in enumerate(word): print(i, value)
0 o 1 n 2 e
Not iterable error. The enumerate() built-in must receive an iterable thing. An argument like an integer will cause an error as an integer cannot be looped over.
Tip We use the pass statement to indicate an empty loop. Enumerate() fails, so this is not reached.
number = 10 # We cannot enumerate an object that is not iterable. for i, value in enumerate(number): pass
Traceback (most recent call last): File "C:\programs\file.py", line 7, in <module> for i, value in enumerate(number): TypeError: 'int' object is not iterable
A powerful tool. Enumerate() is a powerful feature in the Python language. With it we access both indexes and elements themselves.
No information is missing, and we can use a simple for-loop without any complicated index management. With simpler programs, we tend to have fewer program bugs.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 7, 2023 (edit).
© 2007-2024 Sam Allen.