Path: csiph.com!x330-a1.tempe.blueboxinc.net!feeder1.hal-mli.net!news.glorb.com!news2.glorb.com!news-out.octanews.net!indigo.octanews.net!auth.beige.octanews.com.POSTED!not-for-mail From: Paul Rubin Newsgroups: comp.lang.python Subject: Re: Pythonic infinite for loop? References: Date: Fri, 15 Apr 2011 00:24:25 -0700 Message-ID: <7xsjtkx9hy.fsf@ruckus.brouhaha.com> Organization: Nightsong/Fort GNOX User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:tHvJKQjFnxVdDZQUTE57VWmfOLw= MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Lines: 15 NNTP-Posting-Date: 15 Apr 2011 02:24:25 CDT X-Complaints-To: abuse@octanews.net Xref: x330-a1.tempe.blueboxinc.net comp.lang.python:3246 Chris Angelico 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))