Post details: enumerate

10/21/06

Permalink 04:14:57 pm, Categories: Books, Python, 123 words   English (US)

enumerate

I'm reading Core Python Programming 2nd Ed. I sometimes like reading the basic intro chapters even though I have a bit of familiarity with Python. There is always something that I may have missed, and each author has a different writing style which is entertaining to read.

I just found out about the enumerate() builtin. How many times have you done this?

>>> f=['foo', 'bar', 'baz']
>>> for i in range(len(f)):
...   print f[i]
... 
foo
bar
baz

Well you can use enumerate() to have both the index and the value:

>>> f=['foo','bar','baz']
>>> for i, val in enumerate(f):
...   print i, val
... 
0 foo
1 bar
2 baz

Cleaner and no array indexing needed. Oh and how about the Zen of Python?

>>> import this

Comments, Pingbacks:

No Comments/Pingbacks for this post yet...

Leave a comment:

 
 

This is a captcha-picture. It is used to prevent mass-access by robots. (see: www.captcha.net)

You must read and type the 5 chars within 0..9 and A..F, and submit the form.

  

Oh no, I cannot read this. Please, generate a

Viraj's Weblog

Donate to keep this site going!

Amount USD $

June 2011
Mon Tue Wed Thu Fri Sat Sun
<<  <   >  >>
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30      

Search

Categories


Misc

Syndicate this blog XML

What is RSS?

powered by
b2evolution