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 loop
for binds that too
- 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.
Python Enumerate Function returned object is a enumerate object.
Python Enumerate Function Examples
items = ['egg', 'milk', 'butter'] for i in enumerate(items): print(i)
Output: (0, ‘egg’)
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’)
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)
Do comment if you have any doubts and suggestions on this tutorial.
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
All Examples Python Enumerate function are in Python 3, so it may change its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.