empty clause of for loops

Tim Chase python.list at tim.thechases.com
Wed Mar 16 15:39:34 EDT 2016


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:
 items = ["Something here", None]
 item = None
 for item in items:
 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

AltStyle によって変換されたページ (->オリジナル) /