Python Enumerate Function | Why this is useful? 

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 in,cursor a tuple is produced with;(index, element) the loopfor binds that toorow_number and,row respectively.

Python Enumerate Function | Why this is useful? 


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.

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

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. For skip the item you must know about the index in the list, not its value. Its value at the time is unknown for iterate loop.

Output: butter

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.