empty clause of for loops

Peter Otten __peter__ at web.de
Wed Mar 16 09:04:25 EDT 2016


André Roberge wrote:

> On Wednesday, 16 March 2016 07:23:48 UTC-3, 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?
>> 
>> Best,
>> Sven
> 
> for x in my_iterable:
>    # do something
> 
> if not my_iterable:
>    # do something else
> 
> André

This will only work for sequences:

>>> items = iter("abc")
>>> bool(items)
True
>>> list(items)
['a', 'b', 'c']
>>> bool(items) # still true...
True
>>> list(items) # ... but empty
[]





More information about the Python-list mailing list