0

Having a generator is there a way to exhaust the generator without using list()?

This code sample will not print anything:

(print(i) for i in range(10))

It will only do so. If I "invoke" it with list

list((print(i) for i in range(10)))

This is the usual practice I know and which is at least to my knowledge a vastly used technique.

If executed in the REPL, the number 0-9 are printed as expected and I receive a list of 10 None. This makes perfect sense, as print doesn't return anything. However the program needs to store all these Nones in a list only to throw them away just afterwards.

This is very wasteful and subverts the generator's intention not to create large memory peaks.

I can implement my own utility function, which doesn't have this issue:

def do(iterable):
    for _ in iterable:
        pass

do((print(i) for i in range(10)))

Is there a similar functionality in the stdlib, or do I need to use my own utility function?

I admit, this only makes sense, if a generator has side effects and I am not interested in the generated values like in this simple example.

martineau
  • 119,623
  • 25
  • 170
  • 301
hr0m
  • 2,643
  • 5
  • 28
  • 39

0 Answers0