BML
BML

Reputation: 303

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.

Upvotes: 0

Views: 2260

Answers (3)

Mark Julius
Mark Julius

Reputation: 21

This implementation will allow you to make a list of the limit using the range() function

See more about the range function and its arguments here

limit = 5
your_list = []
for x in range(0,limit):
   your_list.append(x)

Upvotes: 2

Stef
Stef

Reputation: 15505

You can change the range of your for-loop to make sure it doesn't go over the limit of the while-loop:

while_loop_max = 5
for_loop_max = 10
test = []
while len(test) < while_loop_max:
  for i in range(min(for_loop_max, while_loop_max - len(test))):
    test.append(i)
print(len(test), test)
# 5 [0, 1, 2, 3, 4]

while_loop_max = 15
for_loop_max = 10
test = []
while len(test) < while_loop_max:
  for i in range(min(for_loop_max, while_loop_max - len(test))):
    test.append(i)
print(len(test), test)
# 15 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4]

Upvotes: -1

Ironkey
Ironkey

Reputation: 2607

So in your original code, you run that for loop inside the loop, it only checks at the end so it goes through code (adds 10 items) and then breaks

here would be a proper way to do that

test = []
while len(test) < 5:
    test.append(1)

print(len(test))
5

and if you want a list of everything in that range just do the following:

list(range(10))

Upvotes: -1

Related Questions