Pythonic infinite for loop?

Chris Angelico rosuav at gmail.com
Fri Apr 15 09:35:20 CEST 2011


On Fri, Apr 15, 2011 at 5:24 PM, Paul Rubin <no.email at nospam.invalid> wrote:
> This does 2 lookups per key, which you could avoid by making the code
> uglier (untested):
>
>   sentinel = object()
>   seq = (dct.get('Keyword%d'%i,sentinel) for i in count(1))
>   lst = list(takewhile(lambda x: x != sentinel, seq))

If I understand this code correctly, that's creating generators,
right? It won't evaluate past the sentinel at all?

That might well be what I'm looking for. A bit ugly, but efficient and
compact. And I can bury some of the ugliness away.

Chris Angelico



More information about the Python-list mailing list