This might be a duplicate, but all I am finding are questions on how for ... else
works.
Python has for ... else
syntax:
for(iteratable):
do_stuff()
conditional break
else:
print("didn't break")
I understand how this works (run the else block when no break was encountered). This is not the question I am asking, but I am looking for something that works like the niave assumption people make when they see it for the first time.
I have come across the situation where I have done the following a number of times:
def foo(iterable):
if iterable:
for i in iterable:
print (i)
else:
print("iterable empty")
This looks fine, we pass in a list:
>>> foo([0,1,2])
0
1
2
>>>
an empty list:
>>> foo([])
iterable empty
>>>
all seems well. Lets pass in a generator:
>>> foo((x for x in range(3)))
0
1
2
>>>
well, this function seems to be working just fine. One last test, what about a generator that has no more values to generate?
>>> foo((x for x in range(0)))
>>>
Hmm. the function hasn't done anything. How interesting.
What method should I use to detect a loop that has run 0 times? Clearly just testing the truthiness of the iterable is not enough. Is there a built-in method for detecting 0 iterations, or will I need to use a counter or flag within the loop to detect an iteration?
Note: this question isn't asking how I can detect an empty generator. Generator specific work-arounds will not work with lists for example.