empty clause of for loops
Chris Angelico
rosuav at gmail.com
Fri Mar 18 17:32:06 EDT 2016
On Sat, Mar 19, 2016 at 7:49 AM, Sven R. Kunze <srkunze at mail.de> wrote:
> On 18.03.2016 20:10, Palpandi wrote:
>>
>> You can do like this.
>>
>> if not my_iterable:
>> <do something>
>> for x in my_iterable:
>> <do something>
>
>
> Thanks for you help here, however as already pointed out, my_iterable is not
> necessarily a list but more likely an exhaustible iterator/generator.
The sentinel option has already been mentioned:
x = sentinel = object()
for x in my_iterable:
...
if x is sentinel:
was_empty
Python does offer another way to do this: instead of a sentinel
object, use an exception.
def process(iterable):
"""Process the iterable. If it was completely empty, raise
UnboundLocalError."""
for x in iterable:
...
x
Just for completeness :)
ChrisA
More information about the Python-list
mailing list