Open In App

Enumerate() in Python

Last Updated : 19 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Often, when dealing with iterators, we also need to keep a count of iterations. Python eases the programmers’ task by providing a built-in function enumerate() for this task. The enumerate () method adds a counter to an iterable and returns it in the form of an enumerating object. This enumerated object can then be used directly for loops or converted into a list of tuples using the list() function.

Syntax: enumerate(iterable, start=0)

Parameters:

  • Iterable: any object that supports iteration
  • Start: the index value from which the counter is to be started, by default it is 0

Return: Returns an iterator with index and element pairs from the original iterable

Example

Here, we are using the enumerate() function with both a list and a string. Creating enumerate objects for each and displaying their return types. It also shows how to change the starting index for enumeration when applied to a string, resulting in index-element pairs for the list and string.

Python
l1 = ["eat", "sleep", "repeat"]
s1 = "geek"

# creating enumerate objects
obj1 = enumerate(l1)
obj2 = enumerate(s1)

print ("Return type:", type(obj1))
print (list(enumerate(l1)))

# changing start index to 2 from 0
print (list(enumerate(s1, 2)))

Output:

Return type: <class 'enumerate'>
[(0, 'eat'), (1, 'sleep'), (2, 'repeat')]
[(2, 'g'), (3, 'e'), (4, 'e'), (5, 'k')]

Using Enumerate Object in Loops

Enumerate() is used with a list called l1. It first prints tuples of index and element pairs. Then it changes the starting index while printing them together. Finally, it prints the index and element separately, each on its own line.

Python
l1 = ["eat", "sleep", "repeat"]

# printing the tuples in object directly
for ele in enumerate(l1):
    print (ele)

# changing index and printing separately
for count, ele in enumerate(l1, 100):
    print (count, ele)

# getting desired output from tuple
for count, ele in enumerate(l1):
    print(count)
    print(ele)

Output:

(0, 'eat')
(1, 'sleep')
(2, 'repeat')
100 eat
101 sleep
102 repeat
0
eat
1
sleep
2
repeat

Accessing the Next Element

In Python, the enumerate() function serves as an iterator, inheriting all associated iterator functions and methods. Therefore, we can use the next() function and __next__() method with an enumerate object.

To access the next element in an enumerate object, you can use the next() function. It takes the enumerate object as input and returns the next value in the iteration.

Python
fruits = ['apple', 'banana', 'cherry']
enum_fruits = enumerate(fruits)

next_element = next(enum_fruits)
print(f"Next Element: {next_element}")

Output:

Next Element: (0, 'apple')

You can call next() again to retrieve subsequent elements:

Python
fruits = ['apple', 'banana', 'cherry']
enum_fruits = enumerate(fruits)

next_element = next(enum_fruits)
print(f"Next Element: {next_element}")

Output:

Next Element: (0, 'apple')

Each time the next() is called, the internal pointer of the enumerate object moves to the next element, returning the corresponding tuple of index and value.


Enumerate() in Python – FAQs

How to use enumerate in Python?

Enumerate in Python is used to loop over an iterable and automatically provide an index for each item. It returns tuples with the index and corresponding value from the iterable. Example:

my_list = ['apple', 'banana', 'cherry']
for index, value in enumerate(my_list):
    print(index, value)
Output:
0 apple
1 banana
2 cherry

This allows you to easily access both the index and the value of each item in the iterable during iteration.

How to get the index using enumerate in Python?

To get the index using enumerate in Python, you can use it in a for loop to iterate over an iterable (such as a list, tuple, or string). Here’s a simple example:

my_list = ['apple', 'banana', 'cherry']
for index, value in enumerate(my_list):
    print(index, value)
Output:
0 apple
1 banana
2 cherry

In this example, enumerate(my_list) returns an enumerate object that generates tuples containing the index and value of each item in my_list during iteration. The for loop unpacks these tuples into index and value variables, allowing you to access both the index and the corresponding value of each element in the list.

How to enumerate in reverse in Python?

To enumerate in reverse in Python, you can combine enumerate with reversed. Here’s an example:

my_list = ['apple', 'banana', 'cherry']
for index, value in enumerate(reversed(my_list)):
    print(len(my_list) - index - 1, value)
Output:
2 cherry
1 banana
0 apple

In this example, reversed(my_list) reverses the order of elements in my_list, and len(my_list) – index – 1 calculates the index in reverse order.

How to start enumerate at 1 in Python?

You can start enumerate at 1 in Python by specifying the start parameter. Here’s an example:

my_list = ['apple', 'banana', 'cherry']
for index, value in enumerate(my_list, start=1):
    print(index, value)
Output:
1 apple
2 banana
3 cherry

In this example, enumerate(my_list, start=1) starts the index at 1 instead of the default 0.

What enumerate returns in Python?

In Python, enumerate() returns an enumerate object, which produces pairs of index and value from an iterable. It adds a counter to the iterable, making it easy to get both the index and the item during iteration. For example:

fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 apple
1 banana
2 cherry


Previous Article
Next Article

Similar Reads

Python VLC Instance - Enumerate the defined audio output devices
In this article we will see how we can get the enumerate audio output devices from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance obje
3 min read
Use enumerate() and zip() together in Python
In this article, we will discuss how to use enumerate() and zip() functions in python. Python enumerate() is used to convert into a list of tuples using the list() method. Syntax: enumerate(iterable, start=0) Parameters: Iterable: any object that supports iterationStart: the index value from which the counter is to be started, by default it is 0 Py
3 min read
Iterate Python Dictionary Using Enumerate() Function
Python dictionaries are versatile data structures used to store key-value pairs. When it comes to iterating through the elements of a dictionary, developers often turn to the enumerate() function for its simplicity and efficiency. In this article, we will explore how to iterate through Python dictionaries using the enumerate() function and provide
3 min read
Difference Between Enumerate and Iterate in Python
In Python, iterating through elements in a sequence is a common task. Two commonly used methods for this purpose are enumerate and iteration using a loop. While both methods allow you to traverse through a sequence, they differ in their implementation and use cases. Difference Between Enumerate And Iterate In PythonBelow, are the Difference Between
4 min read
What Does the Enumerate Function in Python do?
The enumerate function in Python is a built-in function that allows programmers to loop over something and have an automatic counter. It adds a counter to an iterable and returns it as an enumerate object. This feature is particularly useful when you need not only the values from an iterable but also their indices. The basic syntax of enumerate is:
2 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss certain ways in which this problem can be solved.
4 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Practice Tags :
three90RightbarBannerImg