lundi 2 novembre 2020

while loop to break after list reaches certain length

I'm sure this is answered somewhere, but my searches have come up empty.

I want to fill a list until it reaches a certain length, I'm not sure why this doesn't work:

test = []
while len(test) < 5:
    for i in range(10):
        test.append(i)  # I would think this would exit the while loop once i==4 is appended, but it doesn't
len(test)

[out]: 10

The real code has a bunch of ifelse statements in the while loop that will add to list test, and I'd rather not evaluate the length of the list at the end of each conditional statement to cause a break or something similar.

Aucun commentaire:

Enregistrer un commentaire