1 view
in Python
edited

What does for row_number, row in enumerate(cursor): do in Python?

What does enumerate mean in this context?

by (16.8k points)

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

...

foo

bar

baz

>>> for count, elem in enumerate(elements):

...     print count, elem

...

0 foo

1 bar

2 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 foo

43 bar

44 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 count

def 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).

by (106k points)
edited by

The enumerate() function in Python works as follows:

doc = """I like movies. But I don't like the cast. The story is very nice"""

doc1 = doc.split('.')

for i in enumerate(doc1):

print(i)

The output is as follows:-

(0, 'I like movie')

(1, " But I don't like the cast")

(2, ' The story is very nice')