python loops

Kay Schluehr kay.schluehr at gmx.net
Thu Aug 31 15:14:22 EDT 2006


Putty wrote:
> In C and C++ and Java, the 'for' statement is a shortcut to make very
> concise loops.  In python, 'for' iterates over elements in a sequence.
> Is there a way to do this in python that's more concise than 'while'?
>
> C:
> for(i=0; i<length; i++)
>
>
> python:
> while i < length:
> 			i += 1

As AlbaClause had demonstrated you can iterate over indices as well
using the for-statement and the range() function. But you can also
combine iterating over elements and indices at the same time using the
builtin enumerate() type:

for i, item in enumerate(("s1","s2")):
    print i,item

0  s1
1  s2




More information about the Python-list mailing list