2

I have a generator in Python, and I want to loop over it if it has items, and perform a different action if it is empty. Something like

if generator is empty:
    perform some action
else:
    for item in generator:
        perform some actions

I know there is no way to tell if a generator is empty without iterating through it, but it seems that there should still be some nice elegant way to perform this logic. The best I can think of is something along the lines of https://stackoverflow.com/a/664239/161801, which seems very inelegant, I guess because it has to treat the first element of the generator separately from the rest.

Community
  • 1
  • 1
asmeurer
  • 86,894
  • 26
  • 169
  • 240
  • 1
    You could iterate over all the items and set a flag ("there was an item") inside the loop and do the alternate action if the flag was not set – hlt Aug 15 '14 at 19:40
  • @njzk2 I obviously know about that question (I linked to it), but I think it is different. That question is asking if it is possible to know if a generator is empty without iterating through it. I already know that this is not possible due to the way that generators work. I am asking for a clean way to work with this limitation. – asmeurer Aug 15 '14 at 19:41
  • 1
    @asmeurer there are several different answers and approaches in the linked question - what are your problems with them? This doesn't really seem like a separate question. – jonrsharpe Aug 15 '14 at 19:43
  • @asmeurer the answer you linked to is as good as it gets I'm afraid – Jon Clements Aug 15 '14 at 19:45
  • This is what I initially thought (and sometimes wish) that `for else` meant in Python. Unfortunately it means something a little different. – asmeurer Aug 15 '14 at 19:46
  • @asmeurer all the options are in the duplicate - Python hasn't evolved a new way of doing what you want since that was answered... – Jon Clements Aug 15 '14 at 19:50

1 Answers1

4

Just set a flag if the generator is not empty:

isGeneratorEmpty = True
for item in generator:
    isGeneratorEmpty = False
    perform some actions

if isGeneratorEmpty:
    perform some actions
jh314
  • 27,144
  • 16
  • 62
  • 82
  • [Source?](http://stackoverflow.com/a/7971996/1454048) – admdrew Aug 15 '14 at 19:43
  • 3
    @admdrew The logic is pretty straightforward (someone suggested the same thing in the comments), jh314 probably came up with it independently. – dano Aug 15 '14 at 19:45