Re: python loops



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

.



Relevant Pages

  • lxml 1.0.2 and 1.1alpha released
    ... I'm happy to announce the release of lxml 1.0.2 and 1.1alpha. ... extends the ElementTree API significantly to offer support for XPath, RelaxNG, ... * Use Python unicode strings in API. ... Element.iterancestorsiterates over the ancestors of an element ...
    (comp.lang.python.announce)
  • Re: python loops
    ... concise loops. ... In python, 'for' iterates over elements in a sequence. ...
    (comp.lang.python)
  • python loops
    ... concise loops. ... In python, 'for' iterates over elements in a sequence. ...
    (comp.lang.python)
  • Re: counting items
    ... There's a great function called "walk" at that iterates over arbitrary ... It also supplies a recursion-proof way to flatten a list. ... that Python didn't have it. ...
    (comp.lang.python)
  • Re: python loops
    ... concise loops. ... In python, 'for' iterates over elements in a sequence. ...
    (comp.lang.python)