A lambda function (or more accurately, a lambda expression) is simply a function you can define on-the-spot, right where you need it. For example,

f = lambda x: x * 2

is exactly the same thing as

def f(x):
    return x * 2

And when I say exactly, I mean it -- they disassemble to the same bytecode. The only difference between the two is that the one defined in the second example has a name.

Lambda expressions become useful because creating one is not a statement, which means that, as others have already answered, you can do

print iterator(lambda x: x / 4 + 12, 100, 5)

to get precisely what you want.

The main difference between lambda expressions and regular functions, however, is that lambdas are more limited. Lambdas can only contain expressions, not statements. An expression is anything you can put on the right side of an = assignment. (if you want to get more pedantic, Python defines an expression as http://docs.python.org/2/reference/expressions.html )

What this means is a lambda expression can not assign to a variable (in fact, it can't have local variables at all, other than its parameters). It can't print (unless it calls another function that does). It can't have a for loop, a while loop, an if test (other than the ternary operator x if cond else y), or a try/except block.

If you need to do any of those, just define a regular function. In fact, any time you think you want to use a lambda, think twice. Wouldn't the code be more readable if you used a regular function? Isn't that lambda expression something you'd like to reuse somewhere else in your code?

In the end, always do what leads to the most readable and maintainable code. There is no difference between lambdas and normal functions as far as performance is concerned.

Answer from Max Noel on Stack Overflow
Top answer
1 of 2
57

A lambda function (or more accurately, a lambda expression) is simply a function you can define on-the-spot, right where you need it. For example,

f = lambda x: x * 2

is exactly the same thing as

def f(x):
    return x * 2

And when I say exactly, I mean it -- they disassemble to the same bytecode. The only difference between the two is that the one defined in the second example has a name.

Lambda expressions become useful because creating one is not a statement, which means that, as others have already answered, you can do

print iterator(lambda x: x / 4 + 12, 100, 5)

to get precisely what you want.

The main difference between lambda expressions and regular functions, however, is that lambdas are more limited. Lambdas can only contain expressions, not statements. An expression is anything you can put on the right side of an = assignment. (if you want to get more pedantic, Python defines an expression as http://docs.python.org/2/reference/expressions.html )

What this means is a lambda expression can not assign to a variable (in fact, it can't have local variables at all, other than its parameters). It can't print (unless it calls another function that does). It can't have a for loop, a while loop, an if test (other than the ternary operator x if cond else y), or a try/except block.

If you need to do any of those, just define a regular function. In fact, any time you think you want to use a lambda, think twice. Wouldn't the code be more readable if you used a regular function? Isn't that lambda expression something you'd like to reuse somewhere else in your code?

In the end, always do what leads to the most readable and maintainable code. There is no difference between lambdas and normal functions as far as performance is concerned.

2 of 2
10

Yes, you can just use lambda expressions. They are made for this.

iterator(lambda x: x/4+12, 100, 5)

Words from the docs:

Lambdas are usually used to create small, anonymous functions. Actually, they are just a syntatic sugar to define functions. The lambda expression above is exactly the same as your function, only without a name.

If you wish to learn more, Here is some good read:

http://www.diveintopython.net/power_of_introspection/lambda_functions.html
Why use lambda functions?

🌐
Reddit
reddit.com › r/learnpython › how do arguments get passed into lambda functions?
r/learnpython on Reddit: How do arguments get passed into lambda functions?
September 13, 2023 -

I'm trying to learn and use lambda functions, but I'm terribly confused. I understand the examples in tutorials that explicitly pass in values into lambda functions, but I'm stumped by real examples.

For instance, I came across a Reddit post that had the following example:

my_list = [(1, 3), (2, 1), (3, 2)]
sorted(my_list, key=lambda x: x[1])
[(2, 1), (3, 2), (1, 3)]

How does the lambda function take in the second argument as x? Where is that denoted? How do I go about reading lambda functions like this?

Top answer
1 of 5
2
Lots of comments with explanation so I'll just give you the play by play: my_list = [(1, 3), (2, 1), (3, 2)] This is a list of THREE things, not six. It's three tuples: (1, 3) (2, 1) (3, 2) So when the lamda executes, it gets x -- a tuple. And it returns x[1] -- the second number of that tuple. If you were to read it in plain English it would be: sorted(my_list, key=lambda x: x[1]) # "sort all these m'fng tuples by the second number" Play by Play First invocation - lambda gets (1,3) and returns 3 Second invocation - lambda gets (2,1) and returns 1 Third invocation - lambda gets (3,2) and returns 2 sorted() then uses those returned numbers to do the actual sorting. Helpful?
2 of 5
1
pretty much, that lambda function only takes one argument, if it had more than one argument it would be like this: lambda x, y, z: x + y + z lambdas are our inline functions, they exist in C# javascript and etc, they also are called unammed functions because they don't have a name and are only made to be used once. If you do this: my_function = lambda x: x*x you can call it the same way as if it was a regular function like my_function(2) returning 4 But it is not advised because the functions are still missing information that might be useful for you, even if you are recording it into a variable, the function is not receiving a name and other things. You can also pass regular functions without using parenthesis in that argument, like this: def func(x): return x[1] my_list = [(1, 3), (2, 1), (3, 2)] sorted(my_list, key=func) So yes, lambdas are just simplified functions.
Discussions

Understanding lambda in Python and using it to pass multiple arguments - Stack Overflow
After reading everything I can find on lambda expressions in Python, I still don't understand how to make it do what I want. Everyone uses the example: lambda x, y : x + y Why do you need to stat... More on stackoverflow.com
🌐 stackoverflow.com
How to pass a parameter in a lambda function in python? - Stack Overflow
I found a way, but it is not totally ... color as parameter. but still more than one function ... found a solution, similar to the first idea with lambda: command=lambda:set_color("green") for the green-button. lambda just has to be called without the parameter. feeling kind of stupid. ... The command callable doesn't take any arguments. If you want to pass the green ... More on stackoverflow.com
🌐 stackoverflow.com
How do arguments get passed into lambda functions?
Lots of comments with explanation so I'll just give you the play by play: my_list = [(1, 3), (2, 1), (3, 2)] This is a list of THREE things, not six. It's three tuples: (1, 3) (2, 1) (3, 2) So when the lamda executes, it gets x -- a tuple. And it returns x[1] -- the second number of that tuple. If you were to read it in plain English it would be: sorted(my_list, key=lambda x: x[1]) # "sort all these m'fng tuples by the second number" Play by Play First invocation - lambda gets (1,3) and returns 3 Second invocation - lambda gets (2,1) and returns 1 Third invocation - lambda gets (3,2) and returns 2 sorted() then uses those returned numbers to do the actual sorting. Helpful? More on reddit.com
🌐 r/learnpython
13
3
September 13, 2023
How do I pass a lambda to a method as a parameter?
Try Func. The last generic type parameter in Func is the return type, so you need three of them: two for the parameters and one for the return type. More on reddit.com
🌐 r/csharp
27
31
March 6, 2021
🌐
Trey Hunner
treyhunner.com › 2020 › 01 › passing-functions-as-arguments
Passing a function as an argument to another function in Python
January 14, 2020 - When we call that function (with predicate(item)), we pass a single argument to it and then check the truthiness of its return value. A lambda expression is a special syntax in Python for creating ...
🌐
Dataquest
dataquest.io › blog › tutorial-lambda-functions-in-python
Tutorial: Lambda Functions in Python
March 6, 2023 - Usually, we pass a lambda function as an argument to a higher-order function (the one that takes in other functions as arguments), such as Python built-in functions like filter(), map(), or reduce().
🌐
KDnuggets
kdnuggets.com › 2023 › 01 › python-lambda-functions-explained.html
Python Lambda Functions, Explained - KDnuggets
January 6, 2023 - Generally, a lambda function is passed as an argument to a higher-order function such as Python built-in functions – filter(), map(), or reduce().
🌐
Tutorial Teacher
tutorialsteacher.com › python › python-lambda-function
Lambda Functions and Anonymous Functions in Python
... Above, lambda x: x*x defines an anonymous function and call it once by passing arguments in the parenthesis (lambda x: x*x)(5). In Python, functions are the first-class citizens, which means that just as literals, functions can also be passed ...
Find elsewhere
🌐
Quora
quora.com › How-do-you-pass-a-lambda-function-to-another-function
How to pass a lambda function to another function - Quora
Answer (1 of 2): In Python, you can pass a lambda function to another function as an argument just like you would pass any other object. Here’s an example code: def my_func(f, arg): return f(arg) result = my_func(lambda x: x**2, 5) print(result) ...
🌐
Quora
quora.com › How-do-you-pass-parameters-in-the-lambda-function-in-Python
How to pass parameters in the lambda function in Python - Quora
Answer (1 of 2): Syntax of Lambda Function in python- lambda arguments: expression Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned.
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python lambda with multiple arguments
Python Lambda with Multiple Arguments - Spark By {Examples}
May 31, 2024 - You can pass a lambda function as an argument to another function in the same way you pass any other function. Lambda functions are first-class citizens in Python, meaning you can treat them like any other object, including passing them as arguments ...
🌐
Real Python
realpython.com › python-lambda
How to Use Python Lambda Functions – Real Python
December 1, 2023 - The lambda function assigned to full_name takes two arguments and returns a string interpolating the two parameters first and last. As expected, the definition of the lambda lists the arguments with no parentheses, whereas calling the function is done exactly like a normal Python function, with parentheses surrounding the arguments.
🌐
Guru99
guru99.com › home › python › python lambda functions with examples
Python Lambda Functions with EXAMPLES
August 12, 2024 - Here, we define a string that you’ll pass as a parameter to the lambda. We declare a lambda that calls a print statement and prints the result. But why doesn’t the program print the string we pass? This is because the lambda itself returns a function object. In this example, the lambda is not being called by the print function but simply returning the function object and the memory location where it is stored. That’s what gets printed at the console. Python For & While Loops: Enumerate, Break, Continue Statement
Top answer
1 of 2
2

The command callable doesn't take any arguments. If you want to pass the green list into printfunction, just omit the argument, the lambda doesn't need it:

Btn=Button(text="Trigger lambda", command=lambda: printfunction(green))

Now green inside the lambda refers to the global.

If all you wanted to do was to call printfunction with a pre-defined argument, you could use the functools.partial() function; you pass it the function to be called plus any arguments that need to be passed in, and when it's return value is called, it'll do exactly that; call the function with the arguments you specified:

from functools import partial

Btn=Button(text="Trigger lambda", command=partial(printfunction, green))
2 of 2
0

Python is incredibly dynamic, you can modify classes after their definition or create local functions. Example:

class X:
    # generic print function
    def print_color(self, color):
        pass

# dictionary with colors to support
COLORS = {'green': ["#5bd575","#55c76d"]}

# attach various print functions to class X
for name, value in COLORS.items():
    def print_color_x(self, value=value):
        self.print_color(value)
    setattr(X, 'print_color_{}'.format(name), print_color_x)

Note the value=value default parameter. This one is necessary to bind the value within each iteration. Without it, the lookup of value would take place when the function is called, giving you errors about a missing global value or picks up a random one that it happens to find there, but not the one you want. Using functools.partial() could be cleaner, if it allowed creating proper memberfunctions and not just staticfunctions. Note that the example pure Python implementation mentioned in the documentation allows creating memberfunctions, so using that as a replacement is an option.

🌐
DEV Community
dev.to › divshekhar › python-lambda-function-po3
Python Lambda Function - DEV Community
June 19, 2023 - In a lambda function, we use variable-length arguments to accept an arbitrary number of arguments. We denote the variable-length argument by an asterisk (*) before the argument name.
🌐
NBShare
nbshare.io › notebook › 47746562 › Python-Lambda
Python Lambda
... File "<ipython-input-23-c1... section' of this post, Python lambda function can take multiple arguments but lambda functions can also take arguments using *arg and **kwargs...
🌐
LabEx
labex.io › tutorials › python-how-to-pass-arguments-to-lambda-functions-in-python-395087
How to pass arguments to lambda functions in Python | LabEx
By combining lambda functions with built-in Python functions like map(), filter(), and reduce(), you can write more concise and expressive code, especially for simple operations that don't require a full-fledged function definition. By the end of this tutorial, you will have a solid understanding of how to pass arguments to lambda functions in Python.
🌐
Sololearn
sololearn.com › en › Discuss › 29028 › how-to-pass-multiple-args-to-lambda-function-inline-
How to pass multiple args to lambda function inline? | Sololearn: Learn to code for FREE!
you can pass multiple arguments to lambda function like this: print((lambda x,y:x*y)(2,10)) but there is no real reason to do that because you can just write print(2*10) or whatever is the body of your lambda function. and keep in mind that ...
🌐
GeeksforGeeks
geeksforgeeks.org › passing-function-as-an-argument-in-python
Passing function as an argument in Python - GeeksforGeeks
March 1, 2025 - Explanation: lambda x: x ** 2 is passed to fun(), which squares the input 5 to produce 25. A wrapper function (decorator) enhances another function's behavior without modifying it. It takes a function as an argument and calls it within the wrapper.
🌐
Python documentation
docs.python.org › 3 › tutorial › controlflow.html
4. More Control Flow Tools — Python 3.14.3 documentation
Thus, global variables and variables of enclosing functions cannot be directly assigned a value within a function (unless, for global variables, named in a global statement, or, for variables of enclosing functions, named in a nonlocal statement), although they may be referenced. The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object).
🌐
Delft Stack
delftstack.com › home › howto › python › python lambda multiple args
How to Pass Multiple Arguments in Lambda Functions in Python | Delft Stack
February 12, 2024 - In this code snippet, we start with a traditional function, process_data, declared using the def keyword, designed to take a list of numbers as its sole parameter. Within this function, a lambda function named square is introduced using the lambda keyword. This brief lambda function is tailored to operate on a single argument, x, and computes its square, expressed as x ** 2.