Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's lambda with underscore for an argument?

Tags:

python

lambda

People also ask

How do you use lambda as an argument in Python?

Syntax. Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression).

How do you pass two arguments in lambda?

Just like a normal function, a Lambda function can have multiple arguments with one expression. In Python, lambda expressions (or lambda forms) are utilized to construct anonymous functions. To do so, you will use the lambda keyword (just as you use def to define normal functions).

Can Python lambda have default arguments?

Defaults in Python Lambda ExpressionIn Python, and in other languages like C++, we can specify default arguments.

Can lambda have if statement?

Using if else & elif in lambda functionWe can also use nested if, if-else in lambda function.


The _ is variable name. Try it. (This variable name is usually a name for an ignored variable. A placeholder so to speak.)

Python:

>>> l = lambda _: True
>>> l()
<lambda>() missing 1 required positional argument: '_'

>>> l("foo")
True

So this lambda does require one argument. If you want a lambda with no argument that always returns True, do this:

>>> m = lambda: True
>>> m()
True

Underscore is a Python convention to name an unused variable (e.g. static analysis tools does not report it as unused variable). In your case lambda argument is unused, but created object is single-argument function which always returns True. So your lambda is somewhat analogous to Constant Function in math.


it seems to be a function that returns True regardless.

Yes, it is a function (or lambda) that returns True. The underscore, which is usually a placeholder for an ignored variable, is unnecessary in this case.

An example use case for such a function (that does almost nothing):

dd = collections.defaultdict(lambda: True)

When used as the argument to a defaultdict, you can have True as a general default value.


Lambda means a function. The above statement is same as writing

def f(_):
    return True

For lambda a variable needs to be present. So you pass it a variable called _(Similarly you could pass x, y..)


Underscore _ is a valid identifier and is used here as a variable name. It will always return True for the argument passed to the function.

>>>a('123') 
True