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')]
Answer from Barmar on Stack OverflowVideos
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')]
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))
Or
filtered_lst = [x for x in fruit_lst if x[0]=="A"]
Python's built-in filter() function predates generators, and it has persisted, partly out of habit, partly for legacy reasons, and partly because it can be a bit faster than generators.
Having recently tested the performance of filters vs generators in Python 3.13, I found the speed benefit has reversed. In all of my tests, generators were faster than the equivalent filter call - typically by 5 to 10%.
Is it now time to stop using filter() in new code (Python >= 3.13), or are there still cases where it is clearly the better option?