On 16.03.2016 14:09, Tim Chase wrote:
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()
Interesting variation. Good to keep in mind if I encounter a situation
where I need both (empty flag + counter). Thanks. :)
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()
Best,
Sven
--
https://mail.python.org/mailman/listinfo/python-list