Filter function in Python (simple question)

Can somebody explain to me why the following code produces an error:

fruit_lst = ["Apple", "Banana", "Pear", "Apricot", "Orange"]
filtered_lst = filter(lambda x: x if x[0]=="A", fruit_lst)

I'm trying to print out the values which start with the letter A.

Submitted September 13th 2021 by Admin


You Have to add else in inline if statement

for example:

fruit_lst = ["Apple", "Banana", "Pear", "Apricot", "Orange"]
filtered_lst = filter(lambda x: x if x[0]=="A" else 0, fruit_lst)

Admin | 1 month ago


You're getting a syntax error because an if expression has to include else, there's no default value.

But you don't need if here. The callback function of filter() just needs to return a boolean, so just use the comparison.

filtered_lst = filter(lambda x: x.startswith('A'), fruit_lst)

Note that filter() is generally not considered pythonic, conditional list comprehensions are usually preferred.

filtered_lst = [x for x in fruit_lst if x.startswith('A')]

Admin | 1 month ago


Your condition is incomplete. It can be corrected like this.

fruit_lst = ["Apple", "Banana", "Pear", "Apricot", "Orange"]
filtered_lst = filter(lambda x: True if x[0]=="A" else False , fruit_lst)
for s in filtered_lst: print(s)



Admin | 1 month ago


filter works by expecting True or False in order to keep the values in the list, so your way can be fixed to

filtered_lst = list(filter(lambda x: True if x[0]=="A" else False, fruit_lst))

However, its more correct to do it like this:

filtered_lst = list(filter(lambda x: x[0]=="A", fruit_lst))
filtered_lst = [x for x in fruit_lst if x[0]=="A"]

Admin | 1 month ago


The construct if x[0]=="A" is not valid syntax. That's what the error tries to tell you.

The reason it is not valid is that you can not just return only sometimes from the lambda function. You'll have to define what it should return.

Having a look at the filter documentation we can see

filter(function, iterable)
Construct an iterator from those elements of iterable for which function returns true.

So what you want is to have a lambda function that returns either True or False, depending on whether the item should be kept.

 filter(lambda x: x[0]=="A", fruit_lst)

This does the trick. Note that it returns not a list, but a "filter object". If you want to have a list instead of an iterable (e.g. for debug printing), you will have to use list() on this.

By the way (just as a fun fact), if you wanted to use if somewhere in your code, you could also do this:

filtered_lst = [x for x in fruit_lst if x[0]=="A"]

Here, the if without else is allowed because it's a different syntactic construct. It says "take x if it fulfills this, and do not take it otherwise"

Admin | 1 month ago

Relevant Questions

Filter and sort a List

April 10th 2021