Skip to content

Python Enumerate Function | Why this is useful? 

  • by

Python Enumerate Function is a generator that adds an incremental index next to each item of an iterable. In short, it produces the elements of an iterator, as well as an index number in the form of tuples. Enumerate function is inbuilt python, you don’t need to import any module for it.

So for each element,cursor a tuple is produced with;(index, element) the loopfor binds that toorow_number and,row respectively.

Python Enumerate Function | Why this is useful? 

Syntax

enumerate(iterable, start=0)

Parameters values

  • Iterable: any object that supports iteration
  • Start:  Default is 0, the index value from which the counter has to be started. Support only Integer values.

Return Value

Python Enumerate Function returned object is a enumerate object.

Python Enumerate Function Examples 

Simple create a list in python, then use for loop Enumerate() function. Print the output in the console, you can see the tuples with index.

items = ['egg', 'milk', 'butter']

for i in enumerate(items):
    print(i)

Output: (0, ‘egg’)
(1, ‘milk’)
(2, ‘butter’)

Another example of  Enumerate() function with custom indexing.

You can change the indexing as you want, just pass the integer (number) value in the second argument. If you pass string or data types, then an error occurred.

TypeError: 'str' object cannot be interpreted as an integer

items = ['cup', 'pen', 'book']

for i in enumerate(items, 100 ):
    print(i)

Output: (100, ‘cup’)
(101, ‘pen’)
(102, ‘book’)


QA: Interview Questions

What is a use of enumerate() or Why this is useful?

Enumerate() function is used, when you want to iterate over items and you can skip the specific item. To skip the item you must know about the index in the list, not its value. Its value at the time is unknown for the iterated loop.

items = ['egg', 'milk', 'butter', 'juice']

for index, i in enumerate(items):
    if index > 1:  # skip 0 and 1 
        print(i)

Output: butter
juice

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All Examples Python Enumerate function are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading