‘enumerate’ Function

What we usually do if we want to print the content of a list with its index number?

>>> i = 0

>>> for item in items:

… print index, item

… i+= 1

There is actually a short cut to do this. Python has an function called ‘enumerate’. The enumerate function takes a list and returns a (index, item) pair.

>>> print list(enumerate(items))

The reason because we are using a list conversion is, enumerate function is a generator function, which produces one pair at a time. But print cannot be applied to such a function because it print result at once.

As enumerate is a generator function we can apply next() on it.

>>> items = [‘a’, ‘b’, ‘c’, ‘d’]

>>> e= enumerate(items)

>>> e.next()

(0, ‘a’)

>>> e.next()

(0, ‘b’)

Advertisements

About Odol Shinu

I've completed my B Tech in Information Technology in 2010 from Government Engineering College Sreekrishnapuram Palakkad under Calicut University.

Posted on September 5, 2010, in Python. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: