The enumerate() function in Python

The built-in function enumerate() creates and returns an enumerate object from an iterable. When used in a for loop or when the __next__() method is called, the enumerate object returns an index and the element.

Built-in Functions Updated 20 Jan 2023 1 min read

Overview

  • Given an iterable, the built-in function enumerate() returns an iterator which returns an index and the element from the iterable as a tuple upon each call to the __next__().
  • The index is zero based. The index can be modified to start with a non-zero value by passing in the required starting index value to the start parameter of the enumerate() function.

Example

python
# Example Python program that creates an enumerate

            # object from an iterable and prints the contents

            # with an index

            playArea = ["Slide", "Swing", "Seesaw", "Spring rider"]

# Start with index 1

            playEnum = enumerate(playArea, 1)

try:

                # Will print indices 1 and 2

                print(playEnum.__next__())

                print(playEnum.__next__())

    # Will print indices 3 and 4

                for i in playEnum:

                    print(i)

except StopIteration:

                print("Nothing to print")

Output

Output
(1, 'Slide')

            (2, 'Swing')

            (3, 'Seesaw')

            (4, 'Spring rider')