Simple python iteration question

Will Maier willmaier at ml1.net
Tue Aug 14 12:34:30 EDT 2007


On Tue, Aug 14, 2007 at 12:22:04PM -0400, Bryan wrote:
> I just started with python, and have a for loop question
> 
> In c++ (or a number of other languages) I can do this:
> 
> for (int i=0, j=0; i < i_len, j< j_len; ++i, ++j) {}
> 
> If I have this in python:
> l = ['a', 'b', 'c']
> 
> I want to get the value and also an iterator:
> for i,v in len(l), l:
> 	print v
> 	print i
> 
> Or something like this without declaring the iterator outside my loop...
> 
> How do I do this?

Use the enumerate() builtin.

    >>> l = ['a', 'b', 'c']
    >>> for i, v in enumerate(l):
    ...     print i, v
    ... 
    0 a
    1 b
    2 c

-- 

[Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/]



More information about the Python-list mailing list