Function enumerate in python

by Alex
Function enumerate in python

The Python 3 programming language has a built-in enumerate function. From time to time you need to go through the elements of the list and at the same time handle not only the value of the element, but also its sequence number in the list. This is where it’s needed.

Arguments

The enumerate function has two arguments:

  • The object whose elements we are going to search. It does not necessarily have to be a list, it can be, for example, a set or a dictionary.
  • The initial value of the index (start). The default start value is 0.

Returns an iterator on a tuple of two elements: an index and an object element.

Example usage

Here is an example of use. With enumerate, we enumerate the entire list of data. With enumerate we get a tuple of two elements. The num variable will be the index number of the item in the list. The variable val will be the value of the item. We used number 1 as the second argument in the enumerate function so that the indexes start with one instead of zero.

data = [2, 5, 3, 4, 1, 5]
for num, val in enumerate(data, 1):
    print(str(num) + '-th value is equal to ' + str(val))

1st value equals 2
2nd value equals 5
3rd value equals 3
4th value equals 4
5th value equals 1
6th value is 5

Without using enumerate

If you don’t use enumerate in Python 3, you can make your own counter. Give it a starting value and increment it each time the loop passes. For example, like this.

colors = ['red', 'green', 'blue']
ind = 1
for color in colors:
    print(str(ind) + '-th color: ' + color)
    ind += 1

1st color: red
2nd color: green
3rd color: blue
But since Python 3 has such a function as enumerate, we should use it. It simplifies the code and makes it more understandable.

Using next

The function enumerate returns an iterator. Using the next function you can get tuples.

a = [2, 5, 3, 4, 1, 5]
b = enumerate(a)
c = next(b)
print(c)
print(type(c))
print(next(b))

(0, 2)
<class 'tuple'>
(1, 5)

If, at the next call of next, the next element is absent, an exception StopIteration is thrown. To learn more about types of exceptions and how to handle them there is a separate article on the site.

Related Posts

LEAVE A COMMENT