Python enumerate()

Python enumerate() is handy when you need to loop through an item and keep track of its index. It adds a counter to an iterable (like a list or string) and returns it as an enumerate object, which yields pairs of the index and the value for each item.
Table of Contents

Understanding Python enumerate() Function

Python enumerate() function is a built-in function that adds a counter to an iterable and returns it as an enumerate object. This object can then be used directly in loops or converted into a list of tuples, where each tuple contains the count (index) and the corresponding value from the iterable. Python enumerate() is particularly useful when you need both the item and its index while iterating over a sequence, making your code cleaner and more readable than manually managing a counter variable. It simplifies the common task of accessing both elements and their position within the loop.

Syntax of Python enumerate()

enumerate_object = enumerate(iterable, start=0)

Explanation

  • enumerate_object: Variable holds the enumerate object returned by the function.
  • enumerate(): Built-in function that adds a counter to an iterable.
  • iterable: Sequence (e.g., list, tuple, string) you want to iterate over with an index. It is the input parameter for enumerate().
  • start (optional): Integer specifying the starting value of the counter (defaults to 0).

Example of Python enumerate()

my_list = ["apple", "banana", "cherry"]
enumerate_obj = enumerate(my_list)
print(list(enumerate_obj))

Explanation

  • my_list = ["apple", "banana", "cherry"]: Creates a list named my_list.
  • enumerate_obj = enumerate(my_list): Calls enumerate() on my_list and stores the resulting enumerate object in enumerate_obj.
  • print(list(enumerate_obj)): Converts the enumerate object to a list of tuples and prints it.

Output

[(0, ‘apple’), (1, ‘banana’), (2, ‘cherry’)]


enumerate() Parameters

Python enumerate() function accepts two parameters: the iterable and an optional start. The iterable is any object that supports iteration, such as a list, tuple, or string. The start parameter is an integer that specifies the starting value of the counter; it defaults to 0 if not provided. You can use start to begin the count at any integer value, which can be helpful in certain situations where a 0-based index is not desired.

Syntax

enumerate_object = enumerate(iterable, start=0)

Example

my_string = "hello"
enumerate_obj = enumerate(my_string, start=1)
print(list(enumerate_obj))

Explanation

  • my_string = "hello": Creates a string named my_string.
  • enumerate_obj = enumerate(my_string, start=1): Calls enumerate() on my_string starting the count at 1, storing the result in enumerate_obj.
  • print(list(enumerate_obj)): Converts the enumerate object to a list and prints it.

Output

[(1, ‘h’), (2, ‘e’), (3, ‘l’), (4, ‘l’), (5, ‘o’)]


enumerate() Return Value

Python enumerate() function returns an enumerate object. This object is an iterator that yields pairs (tuples) containing a count (from start, which defaults to 0) and the values obtained from iterating over the given iterable. You can use this enumerate object in a for loop or convert it to a list of tuples using list() to see the indexed elements.

Example

my_tuple = ("a", "b", "c")
enumerate_result = enumerate(my_tuple)
print(list(enumerate_result))

Explanation

  • my_tuple = ("a", "b", "c"): Creates a tuple named my_tuple.
  • enumerate_result = enumerate(my_tuple): Calls enumerate() on my_tuple, creating an enumerate object stored in enumerate_result.
  • print(list(enumerate_result)): Converts the enumerate object to a list and prints it.

Output

[(0, ‘a’), (1, ‘b’), (2, ‘c’)]


Loop Over an Enumerate Object

The most common use case for Python enumerate() is in loops. When you loop over an enumerate object using a for loop, each iteration gives you a tuple where the first element is the count (index) and the second element is the value from the original iterable. This allows you to conveniently access each iteration’s index and value without managing a separate counter variable.

Syntax

for index, value in enumerate(iterable, start=0):
    # Loop body

Explanation

  • for index, value in: Unpacks each tuple returned by enumerate() into index and value.
  • enumerate(): Function provides the iterable to loop over.
  • iterable: Sequence you are iterating over with its index. It is passed as input to the enumerate() function.
  • start=0: Starting value for the index (optional).
  • # Loop body: Code to be executed in each iteration, using index and value.

Example

fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

Explanation

  • fruits = ["apple", "banana", "cherry"]: Creates a list named fruits.
  • for index, fruit in enumerate(fruits):: Loop iterates over the fruits list using enumerate(), unpacking each item into index and fruit.
  • print(f"Index {index}: {fruit}"): Prints the index and value for each item.

Output

Index 0: apple
Index 1: banana
Index 2: cherry


Access the Next Element

Within a loop, you can technically access the next element from an enumerate object by manually calling next() on it. However, this is not a typical use case, as the for loop automatically handles this for you. If you need to look ahead in an iterator, it’s often better to work directly with the iterator using iter() and next() rather than Python enumerate. Manually calling next() is rarely needed.

Syntax

enumerate_object = enumerate(iterable)
next_element = next(enumerate_object)

Explanation

  • enumerate_object: Variable holds the enumerate object.
  • enumerate(): Function creates the enumerate object from the iterable.
  • iterable: Sequence you are enumerating. It is passed as input to the enumerate() function.
  • next_element: Variable will store the next element obtained from enumerate_object.
  • next(): Function retrieves the next item from the iterator.

Example

colors = ["red", "green", "blue"]
enum_obj = enumerate(colors)

first_item = next(enum_obj)
print(first_item)

second_item = next(enum_obj)
print(second_item)

Explanation

  • colors = ["red", "green", "blue"]: Creates a list named colors.
  • enum_obj = enumerate(colors): Creates an enumerate object from colors.
  • first_item = next(enum_obj): Retrieves the first item (tuple) from enum_obj using next() and stores it in first_item.
  • print(first_item): Prints the first_item.
  • second_item = next(enum_obj): Retrieves the second item from enum_obj and stores it in second_item.
  • print(second_item): Prints the second_item.

Output

(0, ‘red’)
(1, ‘green’)


Custom Start Index

By providing the start parameter, you can customize the starting index for the count in Python enumerate(). By default, the count starts at 0, but if you set start to a different integer, the count will begin at that value. This can be useful when you want the index to align with a specific numbering scheme or when 0-based indexing is not suitable for your particular use case.

Syntax

for index, value in enumerate(iterable, start=n):
    # Loop body

Explanation

  • for index, value in: Unpacks each tuple from enumerate() into index and value in each iteration.
  • enumerate(): Function adds a counter to the iterable, starting at n.
  • iterable: Sequence you want to enumerate. It is passed as input to the enumerate() function.
  • start=n: Sets the starting value of the counter to n.
  • # Loop body: Code to execute in each iteration.

Example

items = ["sword", "shield", "potion"]
for index, item in enumerate(items, start=1):
    print(f"Item {index}: {item}")

Explanation

  • items = ["sword", "shield", "potion"]: Creates a list named items.
  • for index, item in enumerate(items, start=1):: Loop iterates over items using enumerate(), starting the count at 1.
  • print(f"Item {index}: {item}"): Prints the item number and the item itself.

Output

Item 1: sword
Item 2: shield
Item 3: potion


Conclusion

Python enumerate() is a powerful function for iterating over sequences when you need both the index and value of each element. It simplifies code by automatically handling the counter, making loops cleaner and more readable. Customizing the starting index with the start parameter adds further flexibility. Manually managing the next item with the next() is rarely needed when using enumerate with loop. This function is used mainly inside loops.


Also Read

Python divmod()

Python staticmethod()


Python Reference

python enumerate()

Pirzada Rashid

Senior .NET developer with a Master of Science in Information Technology.
Teaching is one of my passions. It gives me great joy to share my knowledge with others, and I look forward to investing more energy into it.

Table of Contents