Confused: appending to a list

Diez B. Roggisch deets at nospam.web.de
Thu Mar 23 11:41:13 EST 2006


DataSmash wrote:

> I'm confused.  Why is it that when I say "while len(list) < 5:", I get
> 5 items in my list.
> If I say "while len(list) < 6:", I get 6 items in the list and so on.
> I would think if I said "less than 5", I would get 4 items.
> Can anyone explain this?

Yes - you loop until the condition is _not_ fullfilled anymore. Which means
that if the list has a length of five, the len(l) < 6 is true, and
appending makes it len(l) == 6 - which then will fail your condition.

So - you need to loop one time less, by doing

while len(l) < 6 - 1:
    ...

diez

      



More information about the Python-list mailing list