A quirk/gotcha of for i, x in enumerate(seq) when seq is empty

Paul Rubin no.email at nospam.invalid
Fri Feb 24 02:21:32 CET 2012


Alex Willmer <alex at moreati.org.uk> writes:
> i = 0
> for x in seq:
>     # do stuff
>     i += 1
> print 'Processed %i records' % i
>
> Just thought it worth mentioning, curious to hear other options/
> improvements/corrections.

Stephen gave an alternate patch, but you are right, it is a pitfall that
can be easy to miss in simple testing.

A more "functional programming" approach might be:

  def do_stuff(x): ...

  n_records = sum(1 for _ in imap(do_stuff, seq))



More information about the Python-list mailing list