empty clause of for loops

Peter Otten __peter__ at web.de
Thu Mar 17 04:23:32 EDT 2016


Tim Chase wrote:

> On 2016-03-16 16:53, Peter Otten wrote:
>> > item=None
>> > for item in items:
>> >         #do stuff
>>   if item is None:
>> >         #do something else
>> 
>> I like that better now I see it.
> 
> The only problem with that is if your iterable returns None as the
> last item:

I was aware of that. In practice I'd ensure the stronger "sentinel must not 
occur in the iterable":

>   items = ["Something here", None]
>   item = None
>   for item in items:
      assert item is not None
>     print(repr(item))
>   if item is None:
>     print("Empty iterable") # wait, no it's not!
> 
> You'd have to use a sentinel like Ruud mentions further up-list:
> 
>   x = sentinal = object()
>   for x in sequence:
>     print(repr(x))
>   if x is sentinal:
>     print("Empty iterable")
> 
> -tkc





More information about the Python-list mailing list