Python Enumerate

An important thing while dealing with iterators, is we need to keep the count of iterations. Python enumerate is a built-in function that takes care of that.

Python enumerate() does two things:

  • adds a counter value to the iterable and
  • returns a value in the form of the enumerate object.

Python enumerate()

The Python enumerate() method takes two parameters:

  • iterable- a sequence like lists,tuple,string,etc.
  • start- starts counting from this number. If not given, 0 will be considered as a start.

Let’s see an example to understand how enumerate() works:

l=['apple','banana','orange']
obj=enumerate(l)
print(type(obj))
print(obj)

The type of the object returned by enumerate() is <class ‘enumerate’>.

To print the value in a meaningful format, we have to convert the object to a tuple or list. Use tuple() or list() to convert the enumerate object to tuple or list accordingly.

t=('apple','banana','orange') 
obj=enumerate(t) 
print(list(obj))

We can use enumerate() also on strings.

t='abc'
obj=enumerate(t) 
print(tuple(obj))

Below is an example of adding the start parameter to the enumerate().

t='abc'
obj=enumerate(t,10) 
print(tuple(obj))

Since we have given the start parameter, the counting starts from 10 instead of 0.

Looping over enumerate object:

We can use for loop to iterate through the enumerate object.

l=['apple','banana','pineapple']
for value in enumerate(l):
  print(value)

We can also print the counter and item using enumerate() in the below method.

l=['apple','banana','pineapple']
for counter,value in enumerate(l):
  print('The counter is '+str(counter)+' and the value is '+str(value))
Translate »