The Wayback Machine - https://web.archive.org/web/20241115204834/https://www.geeksforgeeks.org/enumerate-in-python/
Open In App

Enumerate() in Python

Last Updated : 25 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 () function 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

Learning the enumerate() function is an essential skill for efficient iteration and data manipulation in Python. To deepen your understanding of Python’s iteration tools and explore advanced programming techniques, consider enrolling in our comprehensive Complete Machine Learning & Data Science Program . This course covers a wide range of Python features, from basic iteration to advanced topics like list comprehensions and generators, empowering you to become a proficient Python developer.

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
next_element = next(enum_fruits)
print(f"Next Element: {next_element}")

Output:

Next Element: (1, 'banana')

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
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
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 0Pyt
4 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
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
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
Context Managers are the tools for wrapping around arbitrary (free-form) blocks of code. One of the primary reasons to use a context manager is resource cleanliness. Context Manager ensures that the process performs steadily upon entering and on exit, it releases the resource. Even when the wrapped code raises an exception, the context manager guar
7 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Python Debugger – Python pdb
Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to the Python standard library. It is actually defined as the class Pdb which internally makes use of bdb(basic debugger functions) and cmd (support for line-oriented command interpreters) modules. The major advantage of pdb is it runs purely in the command line
5 min read
Filter Python list by Predicate in Python
In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method Syntax: filter(predicate, list) where, list
2 min read
Python: Iterating With Python Lambda
In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python. Syntax: lambda variable : expression Where, variable is used in the expressionexpression can be an mathematical expressio
2 min read
Python Value Error :Math Domain Error in Python
Errors are the problems in a program due to which the program will stop the execution. One of the errors is 'ValueError: math domain error' in Python. In this article, you will learn why this error occurs and how to fix it with examples. What is 'ValueError: math domain error' in Python?In mathematics, we have certain operations that we consider un
4 min read
Creating Your Own Python IDE in Python
In this article, we are able to embark on an adventure to create your personal Python Integrated Development Environment (IDE) the usage of Python itself, with the assistance of the PyQt library. What is Python IDE?Python IDEs provide a characteristic-rich environment for coding, debugging, and going for walks in Python packages. While there are ma
3 min read
GeeksforGeeks Python Foundation Course - Learn Python in Hindi!
Python - it is not just an ordinary programming language but the doorway or basic prerequisite for getting into numerous tech domains including web development, machine learning, data science, and several others. Though there's no doubt that the alternatives of Python in each of these respective areas are available - but the dominance and popularit
5 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
Python Image Editor Using Python
You can create a simple image editor using Python by using libraries like Pillow(PIL) which will provide a wide range of image-processing capabilities. In this article, we will learn How to create a simple image editor that can perform various operations like opening an image, resizing it, blurring the image, flipping and rotating the image, and so
13 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (
5 min read
Learn DSA with Python | Python Data Structures and Algorithms
This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with th
15+ min read
Why we write #!/usr/bin/env python on the first line of a Python script?
The shebang line or hashbang line is recognized as the line #!/usr/bin/env python. This helps to point out the location of the interpreter intended for executing a script, especially in Unix-like operating systems. For example, Linux and macOS are Unix-like operating systems whose executable files normally start with a shebang followed by a path to
2 min read
Setting up ROS with Python 3 and Python OpenCV
Setting up a Robot Operating System (ROS) with Python 3 and OpenCV can be a powerful combination for robotics development, enabling you to leverage ROS's robotics middleware with the flexibility and ease of Python programming language along with the computer vision capabilities provided by OpenCV. Here's a step-by-step guide to help you set up ROS
3 min read
What is Python Used For? | 7 Practical Python Applications
Python is an interpreted and object-oriented programming language commonly used for web development, data analysis, artificial intelligence, and more. It features a clean, beginner-friendly, and readable syntax. Due to its ecosystem of libraries, frameworks, and large community support, it has become a top preferred choice for developers in the ind
9 min read
How to Install python-dotenv in Python
Python-dotenv is a Python package that is used to manage & store environment variables. It reads key-value pairs from the “.env” file. How to install python-dotenv?To install python-dotenv using PIP, open your command prompt or terminal and type in this command. pip install python-dotenvVerifying the installationTo verify if you have successful
3 min read
Future of Python : Exploring Python 4.0
The future of Python 4.0 is a topic of great anticipation and speculation within the tech community. Guido van Rossum, the creator of Python, offers exclusive insights into what might lie ahead for this popular programming language. With Python 3.9 approaching its release, many are curious about t the potential for Python 4.0. This article explores
8 min read
Top 10 Python Built-In Decorators That Optimize Python Code Significantly
Python is a widely used high-level, general-purpose programming language. The language offers many benefits to developers, making it a popular choice for a wide range of applications including web development, backend development, machine learning applications, and all cutting-edge software technology, and is preferred for both beginners as well as
12 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python , two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but no
5 min read
Practice Tags :
three90RightbarBannerImg