newbie - infinite loop

Pete Shinners shredwheat at mediaone.net
Mon Mar 19 10:40:51 EST 2001


"Paul Brian" <pbrian at demon.net> wrote
> Surely this should not happen.  Surely the line 3 condition "for every
> element in this list", should not constantly expand but should be set solid
> till the next pass?
>
> What have I done wrong - is it the mutable list v the immutable tuple
> problem (but it should work..surely?) Or is this just the way things are -
> "live with it and do not try anything like this again?"
>
> thanks in advance
> ==============
> uniqueList = ['q']
> line = 'q'
>
> for listElement in uniqueList:   #infinite loop
>     if listElement == line:
>         uniqueList.append(line)
>
> print len(uniqueList)

hello paul. this code should indeed loop forever. let's look and see why...

it sounded like in your message, you only wanted to add items to the
list if they weren't already in it. this section of code is doing
something different. this is going through the list, and everytime it
finds a match for a word, it is adding that word again. the way this
loop is setup, the word will be added to the end of the list, and it
will loop over the appended elements in the list. because of this, the
code will keep finding the same word on the list and keep appending the
same word to the end... infinitely.

obviously this is not the best solution. there are several other ways
you could do this. the way i would probably do it (not the best, likely)
would replace the loop with this;

if line not in uniqueList:
    uniqueList.append(line)

it ends up being somewhat trickier to loop through a list and
make sure an element isn't found. since it sounded like you wanted
to see your loop fixed, i'll take a stab at it. remember, an 'else'
statement in a for loop is executed when the loop is not 'break'ed

for listElement in uniqueList:
    if listElement == list:
        break
else:
    uniqueList.append(list)


good luck, hopefully this was able to teach you a little something
about python. btw, the looping method will definitely be slower than
the "in" version.






More information about the Python-list mailing list