It is strange how much beauty varies for different people. I find the list comprehension much clearer than filter+lambda, but use whichever you find easier.

There are two things that may slow down your use of filter.

The first is the function call overhead: as soon as you use a Python function (whether created by def or lambda) it is likely that filter will be slower than the list comprehension. It almost certainly is not enough to matter, and you shouldn't think much about performance until you've timed your code and found it to be a bottleneck, but the difference will be there.

The other overhead that might apply is that the lambda is being forced to access a scoped variable (value). That is slower than accessing a local variable and in Python 2.x the list comprehension only accesses local variables. If you are using Python 3.x the list comprehension runs in a separate function so it will also be accessing value through a closure and this difference won't apply.

The other option to consider is to use a generator instead of a list comprehension:

def filterbyvalue(seq, value):
   for el in seq:
       if el.attribute==value: yield el

Then in your main code (which is where readability really matters) you've replaced both list comprehension and filter with a hopefully meaningful function name.

Answer from Duncan on Stack Overflow
Top answer
1 of 16
750

It is strange how much beauty varies for different people. I find the list comprehension much clearer than filter+lambda, but use whichever you find easier.

There are two things that may slow down your use of filter.

The first is the function call overhead: as soon as you use a Python function (whether created by def or lambda) it is likely that filter will be slower than the list comprehension. It almost certainly is not enough to matter, and you shouldn't think much about performance until you've timed your code and found it to be a bottleneck, but the difference will be there.

The other overhead that might apply is that the lambda is being forced to access a scoped variable (value). That is slower than accessing a local variable and in Python 2.x the list comprehension only accesses local variables. If you are using Python 3.x the list comprehension runs in a separate function so it will also be accessing value through a closure and this difference won't apply.

The other option to consider is to use a generator instead of a list comprehension:

def filterbyvalue(seq, value):
   for el in seq:
       if el.attribute==value: yield el

Then in your main code (which is where readability really matters) you've replaced both list comprehension and filter with a hopefully meaningful function name.

2 of 16
313

This is a somewhat religious issue in Python. Even though Guido considered removing map, filter and reduce from Python 3, there was enough of a backlash that in the end only reduce was moved from built-ins to functools.reduce.

Personally I find list comprehensions easier to read. It is more explicit what is happening from the expression [i for i in list if i.attribute == value] as all the behaviour is on the surface not inside the filter function.

I would not worry too much about the performance difference between the two approaches as it is marginal. I would really only optimise this if it proved to be the bottleneck in your application which is unlikely.

Also since the BDFL wanted filter gone from the language then surely that automatically makes list comprehensions more Pythonic ;-)

🌐
GeeksforGeeks
geeksforgeeks.org › python › lambda-filter-python-examples
Lambda and filter in Python Examples - GeeksforGeeks
April 8, 2025 - It can take any number of arguments but has only one expression. filter() function: A built-in function that filters elements from an iterable based on a condition (function) that returns True or False.
Discussions

python lambda list filtering with multiple conditions - Stack Overflow
Well, ['1', '2', '4', 'c'] doesn't ... the condition that x[1] != "2". ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... New site design and philosophy for Stack Overflow: Starting February 24, 2026... 4 How to FILTER Python list with multiple ... More on stackoverflow.com
🌐 stackoverflow.com
How do I use filter and lambda in a situation where lambda takes two arguments?
Why does your lambda take two parameters? Rewrite it so it only takes one. In any event, I think writing a list comprehension would be cleaner than using filter(): filtered_divs = [div for div in divs if f(div)] More on reddit.com
🌐 r/learnpython
7
1
October 3, 2020
Filtering list of objects on multiple conditions
Hi all, interested in your approaches and suggestions to this problem. Let's say I have created a custom Player class that contains many attributes… More on reddit.com
🌐 r/learnpython
4
1
July 27, 2023
Multiple conditions in python filter function
No, why would you expect your output to include 2 when your condition explicitly says x!=2? The other condition excludes any even number, since an odd number modulus 2 returns 1, and 1 converts to True. 0 converts to False. So, you're explicitly filtering out any number evenly divisible by 2. More on reddit.com
🌐 r/learnprogramming
4
1
January 7, 2019
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › using filter() with lambda in python
Using filter() with Lambda in Python - Spark By {Examples}
May 31, 2024 - In Python, the filter() function is used to filter elements of an iterable (e.g., a list) based on a certain condition. When combined with the lambda
🌐
Note.nkmk.me
note.nkmk.me › home › python
Filter (Extract/Remove) Items of a List with in Python: filter() | note.nkmk.me
May 15, 2023 - Python for loop (with range, enumerate, zip, etc.) for i in filter(lambda x: x % 2 == 0, l): print(i) # -2 # 0 # 2 ... Note that filter() in Python 2 returns a list, which might cause issues when running Python 2 code in Python 3.
🌐
Finxter
blog.finxter.com › home › learn python blog › python filter(lambda multiple conditions)
Python filter(lambda multiple conditions) - Be on the Right Side of Change
February 5, 2024 - Using the filter() function with a lambda allows us to apply multiple conditions within a single lambda expression by leveraging the logical and. It’s readable and straightforward. numbers = [1, 12, 17, 24, 29, 32] filtered_numbers = ...
🌐
Finxter
blog.finxter.com › how-to-filter-in-python-using-lambda-functions
How to Filter in Python using Lambda Functions? – Be on the Right Side of Change
The second argument is the iterable to be filtered—the lambda function checks for each element in the iterable whether the element pass the filter or not. The filter() function returns an iterator with the elements that pass the filtering condition. lst = [1, 2, 3, 4, 5] # Filter all elements ...
🌐
Medium
codefather-tech.medium.com › python-filter-a-list-with-a-lambda-function-codefather-407d1195ba00
Python: Filter a List With a Lambda Function — CODEFATHER | by Claudio Sabato | Medium
December 8, 2023 - Python provides a built-in function that used with a lambda function allows you to filter a list based on specific conditions: the filter() function. Below you can see the syntax of the filter() function that takes two arguments: the first argument ...
Find elsewhere
🌐
CodeFatherTech
codefather.tech › home › blog › python: filter a list with a lambda function
Python: Filter a List With a Lambda Function - CodeFatherTech
December 8, 2024 - Python provides a built-in function that used with a lambda function allows you to filter a list based on specific conditions: the filter() function. Below you can see the syntax of the filter() function that takes two arguments: the first argument is a function and the second argument is an ...
Top answer
1 of 4
10

x = ['1', '2', '4', 'c'], so x[1]=='2', which makes the expression (x[0] != "1" and x[1] != "2" and x[2] != "3") be evaluated as False.

When conditions are joined by and, they return True only if all conditions are True, and if they are joined by or, they return True when the first among them is evaluated to be True.

2 of 4
8
['1', '2', '4', 'c']

Fails for condition

x[0] != "1"

as well as

x[1] != "2"

Instead of using or, I believe the more natural and readable way is:

lambda x: (x[0], x[1], x[2]) != ('1','2','3')

Out of curiosity, I compared three methods of, er... comparing, and the results were as expected: slicing lists was the slowest, using tuples was faster, and using boolean operators was the fastest. More precisely, the three approaches compared were

list_slice_compare = lambda x: x[:3] != [1,2,3]

tuple_compare = lambda x: (x[0],x[1],x[2]) != (1,2,3)

bool_op_compare = lambda x: x[0]!= 1 or x[1] != 2 or x[2]!= 3

And the results, respectively:

In [30]: timeit.Timer(setup="import timeit,random; rand_list = [random.randint(1,9) for _ in range(4)]; list_slice_compare = lambda x: x[:3] != [1,2,3]", stmt="list_slice_compare(rand_list)").repeat()
Out[30]: [0.3207617177499742, 0.3230015148823213, 0.31987868894918847]

In [31]: timeit.Timer(setup="import timeit,random; rand_list = [random.randint(1,9) for _ in range(4)]; tuple_compare = lambda x: (x[0],x[1],x[2]) != (1,2,3)", stmt="tuple_compare(rand_list)").repeat()
Out[31]: [0.2399928924012329, 0.23692036176475995, 0.2369164465619633]

In [32]: timeit.Timer(setup="import timeit,random; rand_list = [random.randint(1,9) for _ in range(4)]; bool_op_compare = lambda x: x[0]!= 1 or x[1] != 2 or x[2]!= 3", stmt="bool_op_compare(rand_list)").repeat()
Out[32]: [0.144389363900018, 0.1452672728203197, 0.1431527621755322]
🌐
GUVI
guvi.in › hub › python › filtering-a-list-using-the-filter()-method-in-python
Filtering a list using the filter() method in Python
With the 'filter()' function, you ... condition. By specifying a filtering function or lambda expression, the filter() function constructs a new iterable containing only the elements that satisfy the condition....
🌐
Kanoki
kanoki.org › 2022 › 09 › 12 › python-lambda-if-else-elif-with-multiple-conditions-and-filter-list-with-conditions-in-lambda
python lambda if, else & elif with multiple conditions and filter list with conditions in lambda | kanoki
September 12, 2022 - Filtering lists with lambda will return all the elements of the list that return True for the lambda function ... The conditions are joined by and, they return True only if all conditions are True, and if they are joined by or, they return True when the first among them is evaluated to be True
🌐
Delft Stack
delftstack.com › home › howto › python › filter lambda python
The filter() Method and Lambda Functions in Python | Delft Stack
February 23, 2025 - These functions can be used along with the filter method. The lambda functions have the following syntax. ... Parameters should be comma-separated, and the expression should return a boolean result (True or False). Let us understand how to use the two together using a simple example. Refer to the following Python code for the same. array = [11, 23, 13, 4, 15, 66, 7, 8, 99, 10] new_array = list(filter(lambda x: x <= 20, array)) print("Old Array:", array) print("New Array:", new_array)
🌐
HowToDoInJava
howtodoinjava.com › home › python › python list filter() with examples
Python List filter() with Examples
April 3, 2024 - This approach effectively filters ... To filter a list by complex condition, we must extract the condition(s) in a separate function and supply this function to filter()....
🌐
EyeHunts
tutorial.eyehunts.com › home › python filter list by condition
Python filter list by condition - Tutorial - By EyeHunts
January 13, 2023 - Use the built-in function filter function to filter lists by the condition in Python. The filter() function returns a filter object with the filtered elements. filter(func, elements) List comprehension is a shorthand for looping through a list ...
🌐
KDnuggets
kdnuggets.com › 2022 › 11 › 5-ways-filtering-python-lists.html
5 Ways of Filtering Python Lists - KDnuggets
November 14, 2022 - Instead of creating a filter_age function separately, we can write the condition within the `filter()` function using lambda. In our case, we are filtering the age that is greater than 50 and converting the filtered iterator into the list.
🌐
Ceos3c
ceos3c.com › home › python › python filter list – the easiest methods explained
Python Filter List - The Easiest Methods Explained
March 1, 2023 - The syntax for creating list comprehensions is: new_list = [expression for item in iterable if condition] The built-in filter() function returns an object, including the filtered elements.
🌐
iO Flood
ioflood.com › blog › python-filter-list
Using Python to Filter a List: Targeted Guide
June 18, 2024 - We’ve also explored alternative approaches like list comprehension and the itertools module. In essence, the filter() function in Python allows us to create a new list from an existing one, keeping only elements that satisfy a certain condition.
🌐
LabEx
labex.io › tutorials › python-how-to-filter-list-with-conditions-419442
Python - How to filter list with conditions
## Safe filtering with error handling def safe_filter(items, condition): try: return [item for item in items if condition(item)] except Exception as e: print(f"Filtering error: {e}") return [] ## Example usage data = [1, 2, 'three', 4, 5] numeric_data = safe_filter(data, lambda x: isinstance(x, int)) print(numeric_data) ## Output: [1, 2, 4, 5] By mastering these filtering techniques with LabEx, you'll become proficient in manipulating lists with complex conditions in Python.
🌐
Finxter
blog.finxter.com › home › learn python blog › how to filter a list in python?
How to Filter a List in Python? - Be on the Right Side of Change
July 14, 2022 - The most Pythonic and most performant way is to use list comprehension [x for x in list if condition] to filter all elements from a list. Filter with List Comprehension The most Pythonic way of filtering a list—in my opinion—is ...
🌐
FavTutor
favtutor.com › blogs › filter-list-python
Python filter() Function: 5 Best Methods to Filter a List
November 11, 2023 - Filter() function is mostly used for lambda functions to separate lists, tuples, or sets for which a function returns True. It can also be used on nested lists.