What is enumerate() in python

This article aims to provide you with a better understanding of enumerate() in Python. You can understand the concept of enumerating from a bookshelf with different books, and you want to list each book’s title and author and place (index) on the shelf. Enumeration is like having a helper who takes out each book, shows you the cover, and tells you the title, author, and position. However, we can use enumerate() to do something similar in programming. It helps us review a list of items and tells us the position (index) and the value (object) at each position.

To learn more about Python Programming, visit Python Programming tutorials.

Getting started with the Enumerate () function in Python.

In Python, enumerate is a built-in function that takes an iterable object, adds a counter, and returns an enumerated object. Above all, the counter acts as a key to the enumerated object. All in all, this function keeps up with the number of iterations in a loop.

The enumerate() is a Python function that iterates over a sequence of elements while keeping track of their indices and elements. It returns an iterator that produces pairs of indexes and values for each sequence component.

Enumerate () Syntax:

enumerate(iterable, start)

Enumerate () Parameters:

Moreover, the enumerate () function takes two parameters:

  • Iterable: Any object that supports iteration, like a list, a tuple, or a string.
  • Start: A number that defines the starting value of the enumerated object. By default, it is 0.

The enumerated object can be used for loops or converted to a list or tuple using list() and tuple() functions respectively.

However, now you have a basic conceptual understanding of the enumerate() function. Now, consider different approaches and implement the enumerated functions in different scenarios. 

METHODS OF USING THE ENUMERATE ()

Following are the prevalent methods discussed in the context of enumerate function.  

  • Using The Enumerate () Along With List Comprehension 
  • The Enumerate() Function Returns An Enumerate Object.
  • Using The Enumerate () Function To Grab The First N Items From A Dictionary
    • Converting the object to another data structure
  • Using The Enumerate () Within The Def Function
  • Enumerating a string
  • An alternative approach to track the index variable while looping
  • Using Enumerate with a Dictionary
  • Using The Enumerate() With The Numpy Library.
  • Using The Enumerate() With The Pandas Library. 

1) Using the Enumerate () along with list comprehension 

In computing, a list is a collection of values or items. Commas (,) and square brackets ([]) separate the items in the list. Furthermore, Python’s list comprehension statement returns a list from any iterable. Iterables are objects you can iterate over in Python.

In a list comprehension, enumerate() iterates over the numbers list. For each iteration, it returns a tuple containing the index and the value of the current element. These tuples are appended to a new list by the list comprehension.

Moreover, using the enumerate function in Python, you create an enumerate object from a data collection object. 

The enumerate(), in combination with list comprehension, creates a new list that includes the values from an existing list and their corresponding indices. 

numbers = [10, 20, 30, 40, 50]

# Using list comprehension with enumerate and condition
even_numbers_with_indices = [(index, value) for index, value in enumerate(numbers)]

print(even_numbers_with_indices)
[(0, 10), (1, 20), (2, 30), (3, 40), (4, 50)]

– The 1st element in the list, “10”, has an index of 0.

– The 2nd element in the list, “20”, has an index of 1.

– The 3rd element in the list, “30”, has an index of 2.

– The 4th element in the list, “40”, has an index of 3

.- The 5th element in the list, “50”, has an index of 4.

2) The enumerate() function returns an enumerate object.

The enumerate() function creates an enumerate object that contains pairs of indices and elements from the original list. This example pairs each index with the corresponding instrument name from the list. When you print the results, you create an enumerated object from a data collection object. The output indicates that the output is an object of the enumerated type. This object can iterate over the index-element pairs of the original list in a loop or by converting it to another data structure like a list or a dictionary.

# A list of instruments
instrument = ["piano", "drum", "flute"]
 
# Calling enumerate function
enumerated_instrument = enumerate(instrument)
 
# Printing data type of 'enumerated_instrument' variable
print(type(enumerated_instrument)) 
<class 'enumerate'>

3) Using the enumerate () function to grab the first n items from a dictionary

Using the enumerate function, holding the first n items from a dictionary in Python can be possible. A dictionary first n items in a dictionary is retrieved using the for and break iterations in aggregation with the enumerate () function.

Using the enumerate () function, each value within an object is accompanied by a counter, which facilitates accessing items within the collection.

The following example reads from index location 0 (by default) until the break call is made at index location 3.  Key at index location 3 will be excluded, and terminate the process here. 

company_rankings = {
    "rank01": "Apple",
    "rank02": "Google",
    "rank03": "Amazon",
    "rank04": "eBay"
}

for rank, (key, value) in enumerate(company_rankings.items(), start=1):
    if rank == 3:  # Stop after the third company
        break
    print(f"Rank {rank}: {value} (Key: {key})")
Rank 1: Apple (Key: rank01)
Rank 2: Google (Key: rank02)

The loop iterates over the dictionary items using enumerate(), and the variable keeps track of the rank. The loop is set to stop after the third company (rank 3). The output lists the company name, rank, and key for each company up to the third one.

Converting the object to another data structure

In the following example, the enumerate() function on a list of instruments converts the enumerated object to a list and then prints the resulting list. 

The output illustrates the list of tuples where each tuple contains an index and the corresponding instrument name from the original list, showing that the enumerate() object is converted into a list, a list of tuples containing index-element pairs.

You can also change the default index value of the enumerate () function. 

You’re also changing the default starting counter value for enumeration. Here’s how to change Python’s default index value of the enumeration () function.

# A list of instruments
instrument = ["piano", "drum", "flute"]
 
# Calling enumerate function
enumerated_instrument = enumerate(instrument)
 
# Converting enumerated object to list.
enumerated_instrument_list = list(enumerated_instrument)
 
# Printing the list
print(enumerated_instrument_list)
[(0, 'piano'), (1, 'drum'), (2, 'flute')]

Changing the default index value

However, in the following example, the index values start from 5 and continue accordingly for each element in the list.

# A list of instruments
instrument = ["piano", "drum", "flute"]
 
# Calling enumerate function and changing the default counter
enumerated_instrument = enumerate(instrument, 5)
 
# Converting enumerated object to list.
enumerated_instrument_list = list(enumerated_instrument)
 
# Printing the list
print(enumerated_instrument_list)
[(5, 'piano'), (6, 'drum'), (7, 'flute')]

4) Using the Enumerate () within the def function

In the following example, you will learn about creating a def function that takes a sequence and encapsulates enumerate(). The def function works in aggregation to the built-in enumerate() function, but it uses a generator to yield index and item pairs.

def enumeration(sequence, start=0):
    for index, item in enumerate(sequence, start=start):
        yield index, item
data1= ['Student_ID', 'Name', 'Age', 'Grade']

for index, data in enumeration(data1, start=1):
    print(f"Index_location: {index}, Value: {data}")
Index_location: 1, Value: Student_ID
Index_location: 2, Value: Name
Index_location: 3, Value: Age
Index_location: 4, Value: Grade

5) Enumerating a string

In the following example, the list comprehension iterates over each character in the string. It constructs a tuple containing each character’s index and character using a Python one-liner list comprehension approach. 

However, The output is obtained using the enumerate() function, showing that the enumerate() object is converted into a list, which is a list of tuples containing index-char pairs.

word = "Entechin"

# Using list comprehension with enumerate
enumerated_word_list_comprehension = [(index, char) for index, char in enumerate(word)]

# Printing the list
print(enumerated_word_list_comprehension, type(enumerated_word_list_comprehension))
[(0, 'E'), (1, 'n'), (2, 't'), (3, 'e'), (4, 'c'), (5, 'h'), (6, 'i'), (7, 'n')] <class 'list'>

6) An alternative approach to track the index variable while looping

Using enumerate() might be more convenient in most cases, but this demonstrates an alternative approach. You can use enumerate() with a while loop straightforwardly and concisely. In this example, you'll need to manually manage the index variable and the loop's termination condition.
In the following while example, the index variable manually increments within the while loop to iterate over the list. The enumerate() function is not directly used here, but the concept of tracking the index variable while looping through a sequence is still applied. 
names_data = ['Alice  ', 'Bob', 'Charlie', 'Emma  ']
index = 0

while index < len(names_data):
    names = names_data[index]
    print(f"Position: {index}, Names: {names}")
    index += 1
Position: 0, Names: Alice  
Position: 1, Names: Bob
Position: 2, Names: Charlie
Position: 3, Names: Emma 

7) Using Enumerate with a Dictionary

You can enumerate directly over a dictionary iterates over its keys in Python concisely. Using the for…in structure, you can simplify the process of iterating over sequences while simultaneously tracking the index values through the enumerate(). 

The F-string uses for the string formatted output. However, the string literals support and provide a flexible approach to format expressions in a structured format.

ID_data = {'name': 'Emma', 'age': 26, 'ID': 107}
for index, key in enumerate(ID_data):
    print(f"Index: {index}, Key: {key}, Value: {ID_data[key]}")
Index: 0, Key: name, Value: Emma
Index: 1, Key: age, Value: 26
Index: 2, Key: ID, Value: 107

8) Using the enumerate() with the numpy library. 

You can easily handle the case of reading a CSV file with the for..in structure encapsulated with the enumerate () function. It will check the content of each row and print corresponding messages based on whether the rows have enough characters.

The following example reads the CSV file using the csv.reader () function and checks if each row has at least one element before accessing it. If a row has elements, it prints the elements for each row along with the index. 

However, On the contrary, If a row doesn’t have any elements, it executes the else command and prints a message indicating that the row doesn’t have enough characters.

import csv

with open('parts of flowers.csv', 'r') as file:
    reading_file = csv.reader(file)
    for index, row in enumerate(reading_file, start=1):
        if len(row) > 0:  # Check if the row has at least 0 characters
            print(f"Row {index}: \t {row[0]}, {row[1]}")
        else:
            print(f"Row {index} doesn't have enough characters.")
Row 1: 	 stem, roots
Row 2: 	 patels, sepal
Row 3: 	 leaves, flowers

9) Using the enumerate() with the Pandas library. 

The following example uses the pandas to read a CSV file and then iterates through the DataFrame rows using iterrows(). 

The whole process to execute enumerates () in Python in Pandas is as follows:

  • The enumerate() loop iterates through the DataFrame using iterrows() and tracks each iteration’s row_index and row_data.
  • However, it prints the current row’s index and the data from the columns in the csv file.
import pandas as pd

# Load CSV data using pandas
data = pd.read_csv('parts of flowers.csv')

for index, (row_index, row_data) in enumerate(data.iterrows(), start=0):
    print(f"Index: {row_index}, Data: {row_data['parts0']}, {row_data['parts1']}")
Index: 0, Data: stem, roots
Index: 1, Data: patels, sepal
Index: 2, Data: leaves, flowers

Conclusion

In the context of this tutorial, we have explored the basic concept of using the enumerate() function and different approaches to implement it. This approach enables the reading and displays the data from the csv file. Using the enumerate() method with its iterator functions like iterrows() for more complex scenarios. However, we conclude here that Python’s enumerate () function helps us track any data structure’s index and the corresponding value in a conspire, straightforward approach. For any queries, contact us.

Leave a Comment

Your email address will not be published. Required fields are marked *