Pythonic infinite for loop?

Paul Rubin no.email at nospam.invalid
Fri Apr 15 09:24:25 CEST 2011


Chris Angelico <rosuav at gmail.com> writes:
That loop will exit at the first gap in the sequence.  If that's what
you want, you could try (untested):

   from itertools import takewhile

   seq = takewhile(lambda n: ('Keyword%d'%n) in dct, count(1))
   lst = map(dct.get, seq)

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))



More information about the Python-list mailing list