DEV Community

Cover image for Python enumerate
bluepaperbirds
bluepaperbirds

Posted on

Python enumerate

In Python, the enumerate() function takes a collection (e.g. a list) and returns it as an enumerate object.

Consider any list, like the list

grocery = [ 'milk', 'butter', 'bread' ]

How would you get the index of an element?

If you used C, C++, C# or Java before, you use a for loop with an index and use the index to get the value at that location.

Enumerate List and Tuples

In Python, you use enumerate() for that. As parameter you want the iterable, in this case the grocery list.

>>> grocery = [ 'milk', 'butter', 'bread' ]
>>> for idx, val in enumerate(grocery):
...     print("index %d has value %s" % (idx,val))
... 
index 0 has value milk
index 1 has value butter
index 2 has value bread
>>> 

This works for other data too. You can do it for tuples:

>>> grocery = ( 'milk', 'butter', 'bread' )
>>> for idx, val in enumerate(grocery):
...     print("index %d has value %s" % (idx,val))
... 

Enumerate Strings

You can do it for strings. As parameter of the enumerate function, set the string you want to enumerate. Then it outputs the characters with index.

>>> for idx, val in enumerate("hello"):
...     print("index %d has value %s" % (idx,val))
... 

This outputs as expected:

index 0 has value h
index 1 has value e
index 2 has value l
index 3 has value l
index 4 has value o
>>> 

Related links:

Top comments (0)