简体   繁体   中英

Python while loop not breaking when condition met

I realize I'm probably making some really basic syntax error, but I'm having trouble fixing or googling this.

I want a process to stop when a certain limit is reached. Seems like a perfect use case for a while loop. However...

test_list = []

integers = list(range(40))

while len(test_list) < 20:
    for i in integers:
        test_list.append(i)

this will run through the entire integers list rather than stopping halfway through.

len(test_list) < 20 now returns false . shouldn't the loop be breaking when the condition is reached?

The error has occurred as the entire for -loop is executed in the 1st iteration of while -loop. This populates the list and then checks for the condition in the 2nd iteration of your while loop.

This can be solved as below:

test_list = []

integers = list(range(40))

for i in integers:
    test_list.append(i)
    if len(test_list) >= 20:
        break

As already noted, the while condition is not evaluated all the time, but only when the control flow reaches that point, ie before and after the for loop, but not in between. In cases like this (combined while and for ) you could use itertools.takewhile instead:

from itertools import takewhile
for i in takewhile(lambda _: len(test_list) < 20, integers):
    test_list.append(i)

This will execute the loop as long as (a) there are more elements in the iterable, and (b) the condition holds. Thus, test_list ends up as [0, 1, ..., 19]

But of course, in this very particular case, you could also just do test_list = integers[:20] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM