This guide deals with the Python enumerate function and it’s uses, complete with several examples.

The Python enumerate is a useful function to have with dealing with sequences like Lists or Tuples. The enumerate() takes as input a sequence, iterates over it including a counter for every element, returning it as an enumerate object. The benefit of having an enumerate object is that you can place it in a loop to iterated over.

Syntax

enumerate(iterable, start)

Parameters

  • Iterable: any object that can be iterated over.
  • Start: Index value from which the counter is to be started, by default, value is 0.

Example Set 1

Some basic examples of us passing sequences into the enumerate function and printing the output. You have to use the list function on the returned enumerate object to get a readable version.

X = "String"
print(list(enumerate(X)))

X = [5, 7, 4, 2, 4, 7]
print(list(enumerate(X)))

X = ["Apple", "Banana", "Cucumber"]
print(list(enumerate(X)))

X = { 1: "Hat", 2 : "Cat", 3 : "Mat"}
print(list(enumerate(X)))
[(0, 'S'), (1, 't'), (2, 'r'), (3, 'i'), (4, 'n'), (5, 'g')]
[(0, 5), (1, 7), (2, 4), (3, 2), (4, 4), (5, 7)]
[(0, 'Apple'), (1, 'Banana'), (2, 'Cucumber')]
[(0, 1), (1, 2), (2, 3)]

Example Set 2

In this example set we will be iterating over the enumerate objects, printing out their contents.

X = "String"
ob = enumerate(X)

for x in ob:
    print(x)

print("--------")

X = ["Apple", "Banana", "Cucumber"]
ob = enumerate(X)

for x,y in ob:
    print(x,y)
(0, 'S')
(1, 't')
(2, 'r')
(3, 'i')
(4, 'n')
(5, 'g')
--------
0 Apple
1 Banana
2 Cucumber

This marks the end of the Python enumerate Function Article. Any suggestions or contributions for CodersLegacy are more than welcome. Any questions can be asked in the comments section below.

Here’s a link back to the main Python Built-in Functions page.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments