empty clause of for loops

Tim Chase python.list at tim.thechases.com
Wed Mar 16 09:09:39 EDT 2016


On 2016-03-16 11:23, Sven R. Kunze wrote:
> for x in my_iterable:
>      # do
> empty:
>      # do something else
> 
> What's the most Pythonic way of doing this?

If you can len() on it, then the obvious way is

  if my_iterable:
    for x in my_iterable:
      do_something(x)
  else:
    something_else()

However, based on your follow-up that it's an exhaustible iterator
rather than something you can len(), I'd use enumerate:

  count = 0 # have to set a default since it doesn't get assigned
            # if no iteration happens
  for count, x in enumerate(my_iterable, 1):
    do_something(x)
  if not count:
    something_else()

I do a lot of ETL work, and my code often has to report how many
things were processed, so having that count is useful to me.
Otherwise, I'd use a flag:

  empty = True
  for x in my_iterable:
    empty = False
    do_something(x)
  if empty:
    something_else()

-tkc







More information about the Python-list mailing list