empty clause of for loops

alister alister.ware at ntlworld.com
Wed Mar 16 09:25:56 EDT 2016


On Wed, 16 Mar 2016 11:47:31 +0100, Peter Otten wrote:

> Sven R. Kunze wrote:
> 
>> Hi,
>> 
>> a colleague of mine (I write this mail because I am on the list) has
>> the following issue:
>> 
>> 
>> for x in my_iterable:
>>      # do
>> empty:
>>      # do something else
>> 
>> 
>> What's the most Pythonic way of doing this?
> 
> What would you expect?
> 
>>>> class Empty(Exception): pass
> ...
>>>> def check_empty(items):
> ...     items = iter(items)
> ...     try:
> ...         yield next(items)
> ...     except StopIteration:
> ...         raise Empty ...     yield from items ...
>>>> try:
> ...    for item in check_empty("abc"): print(item)
> ... except Empty: print("oops")
> ...
> a
> b
> c
>>>> try:
> ...    for item in check_empty(""): print(item)
> ... except Empty: print("oops")
> ...
> oops
> 
> I'm kidding, of course. Keep it simple and use a flag like you would in
> any other language:
> 
> empty = True:
> for item in items:
>     empty = False ...
> if empty:
>     ...

or even use the loop variable as the flag

item=None
for item in items:
	#do stuff
if ex is None:
	#do something else




-- 
Love means never having to say you're sorry.
		-- Eric Segal, "Love Story"

That's the most ridiculous thing I've ever heard.
		-- Ryan O'Neill, "What's Up Doc?"



More information about the Python-list mailing list