Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #105038
| From | "Sven R. Kunze" <srkunze@mail.de> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: empty clause of for loops |
| Date | 2016-03-16 15:39 +0100 |
| Message-ID | <mailman.211.1458139154.12893.python-list@python.org> (permalink) |
| References | <56E93413.6090108@mail.de> <20160316080939.136c63ee@bigbox.christie.dr> |
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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: empty clause of for loops "Sven R. Kunze" <srkunze@mail.de> - 2016-03-16 15:39 +0100
csiph-web