Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #105038 > unrolled thread

Re: empty clause of for loops

Started by"Sven R. Kunze" <srkunze@mail.de>
First post2016-03-16 15:39 +0100
Last post2016-03-16 15:39 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: empty clause of for loops "Sven R. Kunze" <srkunze@mail.de> - 2016-03-16 15:39 +0100

#105038 — Re: empty clause of for loops

From"Sven R. Kunze" <srkunze@mail.de>
Date2016-03-16 15:39 +0100
SubjectRe: empty clause of for loops
Message-ID<mailman.211.1458139154.12893.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web