Search code examples
pythonone-liner

one liner to go through an iterable (generator)


I encountered some code looking like:

[func(val) for val in iterable]

There is an iterable (in my case a generator) for which a user wants to call a function for each value for its side effects (func could for example just be print) but where the return value is irrelevant.

What I don't like about this approach is, that a temporary list is created, which might consume quite some memory if the generator yields a lot of values.

If the return value of func always evaluates to False, then following works:

any(func(val) for val in iterable)

If the return value of func always evaluates to True, then following works:

all(func(val) for val in iterable)

What would I have to do if the return value of func can evaluate to True or to False

Anything better then forcing the value to False?

The best I came up with is:

any(func(val) and False for val in iterable)

or

all(func(val) or True for val in iterable)

Solution

  • Probably just

    for val in iterable:
       func(val)
    

    is clearest.

    for val in iterable: func(val)
    

    is available if a one-liner is truly necessary.