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 - Explanation: lambda x: x % 2 == 0 returns True for even numbers, and filter() keeps only those elements.
🌐
Medium
medium.com › @rahulkp220 › list-comprehensions-lambda-filter-map-and-reduce-functions-in-python-d7a1bc6cd79d
List Comprehensions, lambda, filter, map and reduce functions in Python | by Rahul Lakhanpal | Medium
April 19, 2016 - >>> map(lambda x: x+1,my_list) [1, 2, 3, 4, 5, 6, 7] filter() function does the same but the difference being that it filters out those elements which satisfy a specific condition.
🌐
Mimo
mimo.org › glossary › python › filter
Python filter(): Syntax, Usage, and Examples
It Needs a Function: The first argument to filter() must be a function (or a lambda) that takes one item as an input and returns True or False. Keeps Items that are True: The new collection will only contain items for which the function returned True. Does Not Change the Original: filter() ...
🌐
freeCodeCamp
freecodecamp.org › news › lambda-functions-in-python
Lambda Functions in Python – How to Use Lambdas with Map, Filter, and Reduce
June 14, 2024 - As a result, the code prints the multiplication results for each pair in the list, showing outputs like "2 3 = 6", "4 5 = 20", and "6 * 7 = 42". The filter function filters elements in an iterable based on a specified predicate.
🌐
Medium
medium.com › data-science › understanding-the-use-of-lambda-expressions-map-and-filter-in-python-5e03e4b18d09
Python’s Lambda Expressions, Map and Filter | by Luciano Strika | TDS Archive | Medium
July 21, 2022 - So to sum up, lambdas can be clunky, but they also add a lot of expression power to your code. Filter and map can be elegant to some, but don’t add a lot to the table in terms of performance (and are seen as less Pythonic than List Comprehensions by some people).
Find elsewhere
🌐
Cisco
ipcisco.com › home › python lambda
Python Lambda | Lambda & Filter Function | Lambda & Map ⋆ IpCisco
January 10, 2022 - Now, let’s learn what are these functions and how can we use them with lambda function. Python Filter function is a function that takes a lambda function as an argument with also another argument.
🌐
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
🌐
Quora
quora.com › Is-it-better-to-use-list-comprehensions-or-filter-lambda-in-Python
Is it better to use list comprehensions or filter() +lambda in Python? - Quora
Answer (1 of 2): LIST COMPREHENSION [code]even = [i for i in range(101) if i%2==0] print(even) [/code]FILTER + LAMBDA [code]even = filter(lambda n : n%2 == 0, range(101)) print(list(even)) [/code]If you want the code which is faster, I would tell you to choose the filter() + lambda. It is the f...
🌐
Reddit
reddit.com › r/learnpython › how do i use filter and lambda in a situation where lambda takes two arguments?
r/learnpython on Reddit: How do I use filter and lambda in a situation where lambda takes two arguments?
October 3, 2020 -

The use of filter, according to me requires a function and a sequence object. Filter then creates a filter object that will eventually be run to filter out those elements which the function returns true on each object in the sequence.

But, I have a lambda that takes two parameters, how do I run filter on lambda and that sequence?

My exact problem is:

The lambda function is:

f = lambda div, keyword : div.attrs.get('class') and keyword in div.attrs.get('class')[0]

Where div would be a beautifulsoup element object and keyword would be a string. And the function f checks if the keyword is there in the class attribute of div or not.

And I have a collection of divs which I want to filter out with f.

Usually I'd write a for loop like this:

filtered_divs = list()

for div in divs:

if f(div, keyword):

filtered_divs.append(div)

Is it worth it to even use lambda and filter in this case? I'm very new to these functions in python and don't know when they should be used instead of a for loop. Thanks

🌐
W3Schools
w3schools.com › python › python_lambda.asp
Python Lambda
Lambda functions are commonly used with built-in functions like map(), filter(), and sorted().
🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-map-lambda.html
Python Map Lambda
Here is the above double-n computation ... function, but not calling it. As a companion to map(), the filter() function takes a function and a list, and returns a subsetted list of the elements where the function returns true....
🌐
LabEx
labex.io › tutorials › python-how-to-apply-a-lambda-function-with-the-filter-function-in-python-415783
How to apply a lambda function with the filter() function in Python | LabEx
Lambda functions are particularly useful when you need a simple function for a short period of time, without the need to define a named function. They can make your code more concise and readable, especially when used in combination with other higher-order functions. The filter() function in Python is a built-in function that takes a function and an iterable (such as a list, tuple, or string) as arguments, and returns an iterator that contains only the elements from the iterable for which the function returns True.
🌐
Medium
medium.com › @engr.tanveersultan53 › map-filter-reduce-and-lambda-function-in-python-3822916f3de8
Map() , Filter() , Reduce() and Lambda Function in Python | by Engr Muhammad Tanveer sultan | Medium
September 26, 2021 - To look more pythonic we generally ... ) function :- It is same like map() function its also takes two arguments first a function and second an iterable object and return the list object of only true values....
🌐
Reddit
reddit.com › r/pythontips › unleashing the power of lambda functions in python: map, filter, reduce
r/pythontips on Reddit: Unleashing the Power of Lambda Functions in Python: Map, Filter, Reduce
July 22, 2023 -

Hello Pythonistas!

I've been on a Python journey recently, and I've found myself fascinated by the power and flexibility of Lambda functions. These anonymous functions have not only made my code more efficient and concise, but they've also opened up a new way of thinking about data manipulation when used with Python's built-in functions like Map, Filter, and Reduce.

Lambda functions are incredibly versatile. They can take any number of arguments, but can only have one expression. This makes them perfect for small, one-time-use functions that you don't want to give a name.

Here's a simple example of a Lambda function that squares a number:

square = lambda x: x ** 2

print(square(5)) # Output: 25

But the real power of Lambda functions comes when you use them with functions like Map, Filter, and Reduce. For instance, you can use a Lambda function with `map()` to square all numbers in a list:

numbers = [1, 2, 3, 4, 5]

squared = list(map(lambda x: x ** 2, numbers))

print(squared) # Output: [1, 4, 9, 16, 25]

You can also use a Lambda function with `filter()` to get all the even numbers from a list:

numbers = [1, 2, 3, 4, 5]

even = list(filter(lambda x: x % 2 == 0, numbers))

print(even) # Output: [2, 4]

And finally, you can use a Lambda function with `reduce()` to get the product of all numbers in a list:

from functools import reduce

numbers = [1, 2, 3, 4, 5]

product = reduce(lambda x, y: x * y, numbers)

print(product) # Output: 120

Understanding and using Lambda functions, especially in conjunction with Map, Filter, and Reduce, has significantly improved my data manipulation skills in Python. If you haven't explored Lambda functions yet, I highly recommend giving them a try!

Happy coding!

🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.sort_values.html
pandas.DataFrame.sort_values — pandas 3.0.6 documentation
>>> df.sort_values(by="col4", key=lambda col: col.str.lower()) col1 col2 col3 col4 0 A 2 0 a 1 A 1 1 B 2 B 9 9 c 3 NaN 8 4 D 4 D 7 2 e 5 C 4 3 F
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › filter
Array.prototype.filter() - JavaScript | MDN
1 month ago - The filter() method is an iterative method. It calls a provided callbackFn function once for each element in an array, and constructs a new array of all the values for which callbackFn returns a truthy value. Array elements which do not pass the callbackFn test are not included in the new array.
🌐
Learn Python
learnpython.org
Learn Python - Free Interactive Python Tutorial
Lambda functions · Multiple Function Arguments · Regular Expressions · Exception Handling · Sets · Serialization · Partial functions · Code Introspection · Closures · Decorators · Map, Filter, Reduce · Parsing CSV Files · DataCamp has tons of great interactive Python Tutorials covering data manipulation, data visualization, statistics, machine learning, and more ·
🌐
CSEstack
csestack.org › home › python lambda function list comprehension | map, filter, reduce
Python Lambda Function List Comprehension | Map, Filter, Reduce
December 10, 2019 - In general, we use Python lambda function when we need a nameless function for a short duration. Mostly it is used to pass as a function object to other functional concepts such as map(), filter() and reduce().
🌐
Better Programming
betterprogramming.pub › lambda-map-and-filter-in-python-4935f248593
Lambda, Map, and Filter in Python | by Rupesh Mishra | Better Programming
March 19, 2023 - More importantly, lambda functions are passed as parameters to functions that expect function object as parameters such as map, reduce, and filter functions.