Welcome, @GeriReshef ! Good question. The basic distinction between creating a function with def and a lambda expression, besides syntactic sugar, is that lambda does so without assigning to a name; in fact, the other common name for a lambda is an anonymous function. If you’re going to create a la… Answer from CAM-Gerlach on discuss.python.org
🌐
W3Schools
w3schools.com › python › python_lambda.asp
Python Lambda
Lambda functions are commonly used with built-in functions like map(), filter(), and sorted().
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-lambda-anonymous-functions-filter-map-reduce
Python Lambda Functions - GeeksforGeeks
Contain only one expression. Result of that expression is returned automatically (no return keyword needed). In this example, a lambda function is defined to convert a string to its upper case using upper().
Published   May 18, 2026
Discussions

What is the purpose of Lambda expressions?
This is a typical example for beginners: x=lambda n:2*n print(x(7)) Otherwise I would create a function: def dbl(n): return 2*n print(dbl(7)) Of course: I can write simply 2*7, but the idea is to save a complex formula in an object once, and reuse it several times. More on discuss.python.org
🌐 discuss.python.org
19
1
December 8, 2021
python - Lambda function in list comprehensions - Stack Overflow
People gave good answers but forgot to mention the most important part in my opinion: In the second example the X of the list comprehension is NOT the same as the X of the lambda function, they are totally unrelated. More on stackoverflow.com
🌐 stackoverflow.com
Is Python a good choice for efficient Lambda functions?

the thing to keep in mind with lambda is you don't get a full vcpu of compute until your function memory is 1,769mb or higher (https://docs.aws.amazon.com/lambda/latest/dg/configuration-memory.html). if your function would benefit from multiple cores, i.e. is multithreaded with parallel busy threads, you'll need to scale up multiples of that to get more vcpus.

other than that, lambda runs on ec2 so the premise of your question is a little weird. runtime choice affects cold start time and how much memory you'll need just for overhead. other than that it has nothing to do with efficiency.

More on reddit.com
🌐 r/aws
5
1
March 23, 2024
lambda functions seem pointless to me
Especially temporary functions that you don't want cluttering your name space. Particularly for sorting and callbacks and such, though there are other uses as well. But they're definitely not an all the time thing. Example: # Name, age people = [("Bob", 43), ("Fred", 62), ] # Sort by age people.sort(key = lambda item: (item[1], item[0])) More on reddit.com
🌐 r/learnpython
10
2
June 21, 2022
🌐
Reddit
reddit.com › r/learnpython › lambda function
r/learnpython on Reddit: Lambda function
April 1, 2024 -

I understand what the lambda function is, its an anonymous function in one line, however why using it, and what really is it? I mean every code I looked at, has it and don't forget map() reduce and filter() function are used with it, what are all these used for and why, I did my research but I still don't understand, (I have a baby's brain 🧠 y'all)

🌐
Amazon Web Services
docs.aws.amazon.com › aws lambda › developer guide › aws lambda functions › programming languages › building lambda functions with python
Building Lambda functions with Python - AWS Lambda
To use these features in Lambda, you can deploy your own Python runtime build with these features enabled, using a container image or custom runtime. In Python 3.12 and later Python runtimes, functions return Unicode characters as part of their JSON response. Earlier Python runtimes return escaped sequences for Unicode characters in responses. For example...
🌐
Python.org
discuss.python.org › python help
What is the purpose of Lambda expressions? - Python Help - Discussions on Python.org
December 8, 2021 - This is a typical example for beginners: x=lambda n:2*n print(x(7)) Otherwise I would create a function: def dbl(n): return 2*n print(dbl(7)) Of course: I can write simply 2*7, but the idea is to save a complex formula in an object once, and ...
🌐
AppSignal
blog.appsignal.com › 2024 › 10 › 16 › how-to-use-lambda-functions-in-python.html
How to Use Lambda Functions in Python | AppSignal Blog
October 16, 2024 - For example, suppose you want to ... Lambda functions to do so: ... # Create a nested lambda function nested_lambda = lambda x: (lambda y: y ** 2)(x) + 1 # Print the result for the value 3 print(nested_lambda(3)) ... Many Python ...
Find elsewhere
🌐
Codecademy
codecademy.com › article › python-lambda-function
Python Lambda Functions Explained (With Examples) | Codecademy
Dive deeper into the unique ways to utilize functions to create cleaner and more efficient software. ... A Python lambda function is an anonymous function that lets you write quick, inline functions without using the def keyword. If you’ve wondered “what is lambda in Python?” - it’s essentially a way to create small functions on the fly for specific tasks.
🌐
The Python Coding Stack
thepythoncodingstack.com › the python coding stack › what's all the fuss about `lambda` functions in python
What's All the Fuss About `lambda` Functions in Python
February 15, 2025 - I'll demonstrate both scenarios: using a standard function and using a lambda function. I'll use this dictionary in the following examples: These are the scores these students got in a test. Let's figure out who passed the test. The pass mark is 5 out of 10. ... Each key in the dictionary scores is passed to check_pass(), and the function's return value is used as the output. Why are the dictionary keys passed to the function and not the key-value pairs? Iteration over dictionaries in Python uses the keys.
🌐
Medium
medium.com › @nirajan_DataAnalyst › lambda-function-in-python-f8d37b5c7e5e
Lambda Function in Python. A lambda function is an anonymous… | by NIRAJAN JHA | Medium
April 24, 2024 - conditional_lambda = lambda x: "Positive" if x > 0 else ("Zero" if x == 0 else "Negative") # Test the lambda function result = conditional_lambda(5) print(result) ... Map in Python is a function that works as an iterator to return a result after ...
🌐
Programiz
programiz.com › python-programming › anonymous-function
Python Lambda/ Function (With Examples)
In the above example, we have assigned a lambda function to the greet_user variable. Here, name after the lambda keyword specifies that the lambda function accepts the argument named name. ... Here, we have passed a string value 'Delilah' to our lambda function. Finally, the statement inside the lambda function is executed. ... The filter() function in Python takes in a function and an iterable (lists, tuples, and strings) as arguments.
🌐
Real Python
realpython.com › python-lambda
How to Use Python Lambda Functions – Real Python
December 1, 2023 - Python lambdas are little, anonymous functions, subject to a more restrictive but more concise syntax than regular Python functions. ... Notes: You’ll see some code examples using lambda that seem to blatantly ignore Python style best practices. This is only intended to illustrate lambda ...
🌐
Medium
medium.com › @brentwash35 › lambda-functions-in-python-the-complete-guide-with-real-world-examples-1f1bab9f4964
Lambda Functions in Python: The Complete Guide With Real-World Examples | by Brent Ochieng | Medium
December 14, 2025 - Python’s built-in functions like map(), filter(), sorted(), and reduce() frequently benefit from lambda functions, allowing you to process data without defining separate named functions.
🌐
TheServerSide
theserverside.com › blog › Coffee-Talk-Java-News-Stories-and-Opinions › create-python-aws-lambda-function-hello-world-tutorial-serverless-how-to-example
Create your first Python AWS Lambda function in minutes
Want to quickly create an AWS Lambda function in Python? This quick Python and AWS tutorial shows how to develop, test and deploy your first Python Lambda function in just a few minutes.
Top answer
1 of 7
370

The first one creates a single lambda function and calls it ten times.

The second one doesn't call the function. It creates 10 different lambda functions. It puts all of those in a list. To make it equivalent to the first you need:

[(lambda x: x*x)(x) for x in range(10)]

Or better yet:

[x*x for x in range(10)]
2 of 7
192

This question touches a very stinking part of the "famous" and "obvious" Python syntax - what takes precedence, the lambda, or the for of list comprehension.

I don't think the purpose of the OP was to generate a list of squares from 0 to 9. If that was the case, we could give even more solutions:

squares = []
for x in range(10): squares.append(x*x)
  • this is the good ol' way of imperative syntax.

But it's not the point. The point is W(hy)TF is this ambiguous expression so counter-intuitive? And I have an idiotic case for you at the end, so don't dismiss my answer too early (I had it on a job interview).

So, the OP's comprehension returned a list of lambdas:

[(lambda x: x*x) for x in range(10)]

This is of course just 10 different copies of the squaring function, see:

>>> [lambda x: x*x for _ in range(3)]
[<function <lambda> at 0x00000000023AD438>, <function <lambda> at 0x00000000023AD4A8>, <function <lambda> at 0x00000000023AD3C8>]

Note the memory addresses of the lambdas - they are all different!

You could of course have a more "optimal" (haha) version of this expression:

>>> [lambda x: x*x] * 3
[<function <lambda> at 0x00000000023AD2E8>, <function <lambda> at 0x00000000023AD2E8>, <function <lambda> at 0x00000000023AD2E8>]

See? 3 time the same lambda.

Please note, that I used _ as the for variable. It has nothing to do with the x in the lambda (it is overshadowed lexically!). Get it?

I'm leaving out the discussion, why the syntax precedence is not so, that it all meant:

[lambda x: (x*x for x in range(10))]

which could be: [[0, 1, 4, ..., 81]], or [(0, 1, 4, ..., 81)], or which I find most logical, this would be a list of 1 element - a generator returning the values. It is just not the case, the language doesn't work this way.

BUT What, If...

What if you DON'T overshadow the for variable, AND use it in your lambdas???

Well, then crap happens. Look at this:

[lambda x: x * i for i in range(4)]

this means of course:

[(lambda x: x * i) for i in range(4)]

BUT it DOESN'T mean:

[(lambda x: x * 0), (lambda x: x * 1), ... (lambda x: x * 3)]

This is just crazy!

The lambdas in the list comprehension are a closure over the scope of this comprehension. A lexical closure, so they refer to the i via reference, and not its value when they were evaluated!

So, this expression:

[(lambda x: x * i) for i in range(4)]

IS roughly EQUIVALENT to:

[(lambda x: x * 3), (lambda x: x * 3), ... (lambda x: x * 3)]

I'm sure we could see more here using a python decompiler (by which I mean e.g. the dis module), but for Python-VM-agnostic discussion this is enough. So much for the job interview question.

Now, how to make a list of multiplier lambdas, which really multiply by consecutive integers? Well, similarly to the accepted answer, we need to break the direct tie to i by wrapping it in another lambda, which is getting called inside the list comprehension expression:

Before:

>>> a = [(lambda x: x * i) for i in (1, 2)]
>>> a1
2
>>> a0
2

After:

>>> a = [(lambda y: (lambda x: y * x))(i) for i in (1, 2)]
>>> a1
2
>>> a0
1

(I had the outer lambda variable also = i, but I decided this is the clearer solution - I introduced y so that we can all see which witch is which).

Edit 2019-08-30:

Following a suggestion by @josoler, which is also present in an answer by @sheridp - the value of the list comprehension "loop variable" can be "embedded" inside an object - the key is for it to be accessed at the right time. The section "After" above does it by wrapping it in another lambda and calling it immediately with the current value of i. Another way (a little bit easier to read - it produces no 'WAT' effect) is to store the value of i inside a partial object, and have the "inner" (original) lambda take it as an argument (passed supplied by the partial object at the time of the call), i.e.:

After 2:

>>> from functools import partial
>>> a = [partial(lambda y, x: y * x, i) for i in (1, 2)]
>>> a0, a1
(2, 4)

Great, but there is still a little twist for you! Let's say we wan't to make it easier on the code reader, and pass the factor by name (as a keyword argument to partial). Let's do some renaming:

After 2.5:

>>> a = [partial(lambda coef, x: coef * x, coef=i) for i in (1, 2)]
>>> a0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: <lambda>() got multiple values for argument 'coef'

WAT?

>>> a0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() missing 1 required positional argument: 'x'

Wait... We're changing the number of arguments by 1, and going from "too many" to "too few"?

Well, it's not a real WAT, when we pass coef to partial in this way, it becomes a keyword argument, so it must come after the positional x argument, like so:

After 3:

>>> a = [partial(lambda x, coef: coef * x, coef=i) for i in (1, 2)]
>>> a0, a1
(2, 4)

I would prefer the last version over the nested lambda, but to each their own...

Edit 2020-08-18:

Thanks to commenter dasWesen, I found out that this stuff is covered in the Python documentation: https://docs.python.org/3.4/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result - it deals with loops instead of list comprehensions, but the idea is the same - global or nonlocal variable access in the lambda function. There's even a solution - using default argument values (like for any function):

>>> a = [lambda x, coef=i: coef * x for i in (1, 2)]
>>> a0, a1
(2, 4)

This way the coef value is bound to the value of i at the time of function definition (see James Powell's talk "Top To Down, Left To Right", which also explains why mutable default values are shunned).

🌐
Analytics Vidhya
analyticsvidhya.com › home › learn how to use lambda functions in python easily and effectively
Learn How to Use Lambda Functions in Python Easily and Effectively
December 1, 2024 - We can also use lambda functions in a list comprehension. In the following example, I have created a random dataset containing information about a family of 5 people with their id, names, ages, and income per month.
🌐
SentinelOne
sentinelone.com › blog › aws-lambda-with-python
AWS Lambda With Python: A Simple Introduction With Examples
April 13, 2024 - We’ll point an API to our Lambda function. Before we do this, we’ll need to go back to the IAM section in the AWS Console and give our user access to AmazonAPIGatewayAdministrator (to create the API Gateway) and AmazonAPIGatewayInvokeFullAccess (to invoke the endpoint): Now that the Serverless framework can also configure the API Gateway service, we can add a trigger to our serverless.yml: service: email-validator provider: name: aws runtime: python3.8 functions: main: handler: handler.validate events: - http: POST /email/validate
🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-map-lambda.html
Python Map Lambda
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. For example, given a list of strings, return a list of the strings where the length is greater than 3: >>> strs = ['apple', 'and', 'a', 'donut'] >>> >>> list(filter(lambda s: len(s) > 3, strs)) ['apple', 'donut']
🌐
DataCamp
datacamp.com › tutorial › python-lambda-functions
Python Lambda Functions: A Beginner’s Guide | DataCamp
January 31, 2025 - Lambda functions are ideal for ... the same functionality can be achieved with a concise one-liner lambda function assigned to a variable: is_even = lambda x: x % 2 == 0....
🌐
PW Skills
pwskills.com › blog › python › python lambda function
Python Lambda Function: Syntax, Examples, And Use Cases
February 20, 2026 - A regular function (def) has a name, can be used again, and can have more than one line of complicated logic. Yes. You can pass as many arguments as you like by putting commas between them. For example, lambda a, b, c: a + b + c.
🌐
Simplilearn
simplilearn.com › home › resources › software development › learn lambda in python with syntax and examples
Learn Lambda in Python with Syntax and Examples
May 14, 2024 - Lambda in python is used to define an anonymous function in Python. Know how Python Lambda Function is used with syntax, examples, and more in this tutorial.
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States