What does enumerate() mean? What does enumerate() mean? python python

What does enumerate() mean?


The enumerate() function adds a counter to an iterable.

So for each element in cursor, a tuple is produced with (counter, element); the for loop binds that to row_number and row, respectively.

Demo:

>>> elements = ('foo', 'bar', 'baz')>>> for elem in elements:...     print elem... foobarbaz>>> for count, elem in enumerate(elements):...     print count, elem... 0 foo1 bar2 baz

By default, enumerate() starts counting at 0 but if you give it a second integer argument, it'll start from that number instead:

>>> for count, elem in enumerate(elements, 42):...     print count, elem... 42 foo43 bar44 baz

If you were to re-implement enumerate() in Python, here are two ways of achieving that; one using itertools.count() to do the counting, the other manually counting in a generator function:

from itertools import countdef enumerate(it, start=0):    # return an iterator that adds a counter to each element of it    return zip(count(start), it)

and

def enumerate(it, start=0):    count = start    for elem in it:        yield (count, elem)        count += 1

The actual implementation in C is closer to the latter, with optimisations to reuse a single tuple object for the common for i, ... unpacking case and using a standard C integer value for the counter until the counter becomes too large to avoid using a Python integer object (which is unbounded).


It's a builtin function that returns an object that can be iterated over. See the documentation.

In short, it loops over the elements of an iterable (like a list), as well as an index number, combined in a tuple:

for item in enumerate(["a", "b", "c"]):    print item

prints

(0, "a")(1, "b")(2, "c")

It's helpful if you want to loop over a sequence (or other iterable thing), and also want to have an index counter available. If you want the counter to start from some other value (usually 1), you can give that as second argument to enumerate.


I am reading a book (Effective Python) by Brett Slatkin and he shows another way to iterate over a list and also know the index of the current item in the list but he suggests that it is better not to use it and to use enumerate instead. I know you asked what enumerate means, but when I understood the following, I also understood how enumerate makes iterating over a list while knowing the index of the current item easier (and more readable).

list_of_letters = ['a', 'b', 'c']for i in range(len(list_of_letters)):    letter = list_of_letters[i]    print (i, letter)

The output is:

0 a1 b2 c

I also used to do something, even sillier before I read about the enumerate function.

i = 0for n in list_of_letters:    print (i, n)    i += 1

It produces the same output.

But with enumerate I just have to write:

list_of_letters = ['a', 'b', 'c']for i, letter in enumerate(list_of_letters):    print (i, letter)


matomo