Sangita Paul
Sangita Paul

Reputation: 137

Else part I don't want to capture nothing in Ternary Operation in Python

I have tried with short program to print list items whose length greater than 2.

def mygenerator(func,*args):
       for arg in args:
            for item in arg:
                yield func(item)
print(list(mygenerator(lambda x: x if x.__len__()> 2 else None ,['ab', 'abc', 'aba', 'xyz', '1991']))) 

It is not solved not purpose I capture none in my list when condition is failed.

Output :- [None, 'abc', 'aba', 'xyz', '1991']

I know with filter I can do that operation but what is missing in my generator:-

print(list(filter(lambda x: x if x.__len__()> 2 else None ,['ab', 'abc', 'aba', 'xyz', '1991'])))

Could you please guide me what I needs to modify. How can I use Ternary Operation without else.

Upvotes: 0

Views: 46

Answers (1)

furas
furas

Reputation: 142641

Use normal filter() and return True or False

print(list(filter(lambda x: len(x)> 2 ,['ab', 'abc', 'aba', 'xyz', '1991'])))

OR use list comprehension with if at the end

print( [x for x in ['ab', 'abc', 'aba', 'xyz', '1991'] if len(x) > 2] )

EDIT

Your generator with if inside function (but this recreates filter)

def mygenerator(func, *args):
    for arg in args:
        for item in arg:
            if func(item):
                yield item

print(list(mygenerator(lambda x: len(x) > 2, ['ab', 'abc', 'aba', 'xyz', '1991']))) 

Upvotes: 1

Related Questions