Home » Python » What does enumerate mean?

What does enumerate mean?

Posted by: admin November 1, 2017 Leave a comment

Questions:

I am using tkinter in Python and came across the following code:

for row_number, row in enumerate(cursor):

I was wondering whether anyone could explain what enumerate means in this context?

Answers:

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

Questions:
Answers:

It’s a builtin generator function, see http://docs.python.org/2/library/functions.html#enumerate .

In short, it yields the elements of an iterator, as well as an index number:

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 an interator, 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.

Questions:
Answers:
# import modules
import numpy as np
import pandas as pd

# generate some time series for six different categories
myts = list("abcdefgh")

tsd = np.random.randn(2000)

tgt = np.random.choice(myts, 2000)

for i, l in enumerate(myts):
    tsd[tgt == l] += i // 2

# Populate into data frame
df = pd.DataFrame(dict(score = tsd, group = tgt))

# Check the results
df.head()

Which results into:

group   score
0   d   1.658331
1   h   3.020331
2   d   0.253232
3   d   1.494033
4   e   3.533548