Python enumerate (For Index, Element)

Use the enumerate function to access tuples containing indexes and elements from an iterable.
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.Built-ins
Let us start. This example uses a string list. Enumerate() acts on any iterable, even a tuple, but a list is a common target for it.

Unpack: We can unpack the tuple directly in the for-loop clause. Or we can receive the tuple and access its items later.

Python program that uses enumerate 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]) Output 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.
Python program that enumerates over string 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) Output 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.

Pass: We use the pass statement to indicate an empty loop. Enumerate() fails, so this is not reached.

Python program that causes not iterable error number = 10 # We cannot enumerate an object that is not iterable. for i, value in enumerate(number): pass Output Traceback (most recent call last): File "C:\programs\", 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