Pythonic infinite for loop?

Chris Angelico rosuav at
Fri Apr 15 05:58:22 CEST 2011

Thanks for the responses, all! In its strictest sense,
itertools.count() seems to be what I'm after, but may not be what I

On Fri, Apr 15, 2011 at 12:33 PM, Steven D'Aprano
<steve+comp.lang.python at> wrote:
> No. But you can use an itertools.count([start=0]) object, and then catch
> the KeyError when you pass the end of the dict. But assuming keys are
> consecutive, better to do this:
> lst = [parse_kwdlist(dct["Keyword%d"%i]) for i in xrange(1, len(dct)+1)]

Ah, didn't think to use len(dct) as the top! And yes, the keys will be
consecutive (or rather, if someone omits Keyword5 then I can
justifiably ignore Keyword6).

> If you don't care about the order of the results:
> lst = [parse_kwdlist(value) for value in dct.values()]

No, order will matter (I have to pick up the first N that fit certain
conditions, after parsing).

The dictionary is potentially a lot larger than this particular set of
values (it's a mapping of header:value for a row of a user-provided
CSV file). Does this make a difference to the best option? (Currently
I'm looking at "likely" figures of 60+ keys in the dictionary and 3-8
postage options to pick up, but both of those could increase
significantly before production.)

Efficiency is important, though not king; this whole code will be
inside a loop. But readability is important too.

I can't just give all of dct.values() to parse_kwdlist; the function
parses a particular format of text string, and it's entirely possible
that other values would match that format (some of them are pure
free-form text). This has to get only the ones starting with Keyword,
and in order. Steven, the line you suggested:

lst = [parse_kwdlist(dct["Keyword%d"%i]) for i in xrange(1, len(dct)+1)]

will bomb with KeyError when it hits the first one that isn't present,
I assume. Is there an easy way to say "and when you reach any
exception, not just StopIteration, return the list"? (I could wrap the
whole "lst = " in a try/except, but then it won't set lst at all.)

If not, I think I'll go with:

for i in xrange(1,len(dct)+1):

and otherwise as per OP. Having a check for "if key%d in dct" going
all the way up seems like an odd waste of effort (or maybe I'm wrong

Chris Angelico

More information about the Python-list mailing list