Python enumerate()

The enumerate() function adds a counter to an iterable and returns it as an enumerate object (iterator with index and the value).

Example

languages = ['Python', 'Java', 'JavaScript']

# enumerate the list enumerated_languages = enumerate(languages)
# convert enumerate object to list print(list(enumerated_languages)) # Output: [(0, 'Python'), (1, 'Java'), (2, 'JavaScript')]

enumerate() Syntax

enumerate(iterable, start=0)

enumerate() Arguments

The enumerate() function takes two arguments:

  • iterable - a sequence, an iterator, or objects that support iteration.
  • start (optional) - enumerate() starts counting from this number. If start is omitted, 0 is taken as start.

enumerate() Return Value

The enumerate() function adds a counter to an iterable and returns it. The returned object is an enumerate object.

An enumerate object is an iterator that produces a sequence of tuples, each containing an index and the value from the iterable.

We can convert enumerate objects to lists and tuples using list() and tuple() functions, respectively.


Example: Python enumerate()

grocery = ['bread', 'milk', 'butter']

# enumerate the list enumerateGrocery = enumerate(grocery)
print(list(enumerateGrocery))
# set default counter to 10 enumerateGrocery = enumerate(grocery, 10)
print(list(enumerateGrocery))

Output

[(0, 'bread'), (1, 'milk'), (2, 'butter')]
[(10, 'bread'), (11, 'milk'), (12, 'butter')]

Note: We can change the default counter in enumerate() as per our need.


Example: Loop Over an Enumerate Object

grocery = ['bread', 'milk', 'butter']

for item in enumerate(grocery):
  print(item)

print()

# loop over an enumerate object for count, item in enumerate(grocery): print(count, item)
print()
# change the default counter and loop for count, item in enumerate(grocery, 100): print(count, item)

Output

(0, 'bread')
(1, 'milk')
(2, 'butter')

0 bread
1 milk
2 butter

100 bread
101 milk
102 butter

To learn more about loops, visit Python for loop.


Access the Next Element

In Python, we can use the next() function to access the next element from an enumerated sequence. For example,

grocery = ['bread', 'milk', 'butter']

enumerateGrocery = enumerate(grocery)

# accessing the next element next_element = next(enumerateGrocery)
print(f"Next Element: {next_element}")

Output

Next Element: (0, 'bread')

To learn more, visit Python next().

Also Read:

Did you find this article helpful?