Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (45.3k points)
edited by

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

What does enumerate mean in this context?

2 Answers

0 votes
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).

0 votes
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')

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
asked May 11, 2020 in Python by Sudhir_1997 (55.5k points)
0 votes
1 answer
asked Feb 11 in Python by Rekha (2.2k points)
0 votes
1 answer
asked Feb 4 in Python by Rekha (2.2k points)
0 votes
1 answer
asked Dec 16, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.6k users

Browse Categories

...