The rap against "while True:" loops

Steven D'Aprano steven at
Wed Oct 14 00:24:11 CEST 2009

On Tue, 13 Oct 2009 14:59:04 -0700, Mensanator wrote:

> And I'm not saying John nor the OP should stop using what works for
> them. But there are certainly valid reasons for "don't use while True"
> to be on the "Best Practices" list.

"Valid"? Well, maybe. But none of them are convincing to me. The best I 
have seen is that loops should have a single entry point and a single 
exit point, to make it easier to reason about pre- and post-conditions. 
But frankly I'm not convinced that's true -- or at least, multiple exists 
shouldn't *necessarily* leader to difficulty in reasoning about the post-

> After all, how many times hve you put 'break' in a loop comprehension?

What's a loop comprehension?

Do you mean *list* comprehensions? List comps aren't supposed to be a 
general purpose replacement for for-loops. They are a deliberately cut-
down version which is easier to read, write and execute than a pure 
Python for-loop:

>>> from timeit import Timer
>>> Timer("""L = []
... for i in range(20):
...     L.append(2*i-1)
... """, '').repeat()
[9.7169408798217773, 9.4620440006256104, 9.4636049270629883]
>>> Timer('[2*i-1 for i in range(20)]', '').repeat()
[5.6287829875946045, 5.8934588432312012, 5.7950780391693115]

But the consequence of that simplicity and speed is that they're not as 
general as a for-loop. This was a design decision. But change the design 
and you could have something like this:

[expr for name in seq until cond]

which breaks when cond becomes true.


More information about the Python-list mailing list