Home » Python Tutorial » Python Enumerate

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))
READ  Python Local and Global Variables
Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions
Core Java Interview Questions

AD Blocker Detected !

Advertisements help running this website for free.

To view the content please disable AdBlocker and refresh the page.

Wait !!!

You can Crack Technical Interviews of Companies like Amazon, Google, LinkedIn, Facebook, PayPal, Flipkart, etc

Anisha was able to crack Amazon after practicing questions from TutorialCup