2

Say I have the following loop:

i = 0
l = [0, 1, 2, 3]
while i < len(l):
    if something_happens:
         l.append(something)
    i += 1

Will the len(i) condition being evaluated in the while loop be updated when something is appended to l?

4
  • 3
    If that's your code, it'll never exit for a different reason: at the beginning of the loop, i < len(l). As the loop continues, l can only get bigger, and i stays the same. Commented May 14, 2009 at 17:23
  • @orjac i think he omitted the "i" increment on purpose for the sake of brevety Commented May 14, 2009 at 17:27
  • yes... i know that you have to increment i. Commented May 14, 2009 at 17:29
  • 3
    I assumed that, if it's worth asking SO, he'd tried it and the loop never exited -- which is why I was looking for other bugs. ;) Commented May 14, 2009 at 19:02

2 Answers 2

14

Yes it will.

Sign up to request clarification or add additional context in comments.

Comments

3

Your code will work, but using a loop counter is often not considered very "pythonic". Using for works just as well and eliminates the counter:

>>> foo = [0, 1, 2]
>>> for bar in foo:
        if bar % 2: # append to foo for every odd number
            foo.append(len(foo))
        print bar

0
1
2
3
4

If you need to know how "far" into the list you are, you can use enumerate:

>>> foo = ["wibble", "wobble", "wubble"]
>>> for i, bar in enumerate(foo):
        if i % 2: # append to foo for every odd number
            foo.append("appended")
        print bar

wibble
wobble
wubble
appended
appended

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.