Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally yield nothing in one line in python

I have generator like

def not_nones(some_iterable):
    for item in some_iterable:
        if item is not None:
            yield item

But since "flat is better than nested", I would like to do this in one line, like:

def not_nones(some_iterable):
    for item in some_iterable:
        yield item if item is not None else None

But this will actually make None an item of the generator. Is it possible to yield nothing in a one-liner anyway?


1 Answers

You could just return a generator expression:

def not_nones(iterable):
    return (item for item in iterable if item is not None)

Or for a real one-liner:

not_nones = lambda it: (i for i in it if i is not None)

which at this point is getting more into code-golf territory.

But really, there's not much wrong with your current code; it does what it needs to do, in a reasonable way. Your code is what I would have written in this situation.

like image 140
nneonneo Avatar answered Nov 25 '25 14:11

nneonneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!