Python's lambda with underscore for an argument?

Question:

What does the following code do?

a = lambda _:True

From what I read and tested in the interactive prompt, it seems to be a function that returns always True.

Am I understanding this correctly? I hope to understand why an underscore (_) was used as well.

Asked By: laycat

||

Answers:

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
Answered By: haccks

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.

Answered By: miku

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
Answered By: user1907906

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..)

Answered By: hyades

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.

Answered By: Ɓukasz Rogalski

Below is the line of code in question:

a = lambda _:True

It creates a function having one input parameter: _. Underscore is a rather strange choice of variable name, but it is just a variable name. You can use _ anywhere, even when not using lambda functions. For example, instead of….

my_var = 5
print(my_var)

You could write:

_ = 5
print(_)

However, there was a reason that _ was used as the name of parameter name instead of something like x or input. We’ll get to that in a moment.

First, we need to know that the lambda-keyword constructs a function, similar to def, but with different syntax. The definition of the lambda function, a = lambda _:True, is similar to writing:

def a(_):
    return True

It creates a function named a with an input parameter _, and it returns True. One could have just as easily written a = lambda x:True, with an x instead of an underscore. However, the convention is to use _ as a variable name when we do not intend to use that variable. Consider the following:

for _ in range(1, 11):
    print('pear')

Notice that the loop index is never used inside of the loop-body. We simply want the loop to execute a specified number of times. As winklerrr has written, “the variable name _ is […] like a “throw-away-variable”, just a placeholder which is of no use. “

Likewise, with “a = lambda x:True the input parameter is not used inside the body of the function. It does not really matter what the input argument is, as long as there is one. The author of that lambda-function wrote _ instead of something like x, to indicate that the variable would not be used.

Note that the lambda does have an argument; So, writing

a(), will raise an error.

If you want a lambda with no argument write something like this:

 bar = lambda: True

Now calling bar(), with no args, will work just fine.
A lambda which takes no arguments need not always return the same value:

import random
process_fruit = lambda : random.random()

The lambda function above is more complex that just a something which always returns the same constant.

One reason that programmers sometimes us the lambda keyword instead of def is for functions which are especially short and simple. Note that a lambda definition can usually fit all on one line, whereas, it is difficult to do the same with a def statement. Another reason to use lambda instead of def sf when the function will not be used again. If we don’t want to call the function again later, then there is no need to give the function a name. For example consider the following code:

def apply_to_each(transform, in_container):
out_container = list()
for idx, item in enumerate(container, 0):
out_container[idx] = transform(item)
return out_container

Now we make the following call:

squares  = apply_to_each(lambda x: x**2 range(0, 101))

Notice that lambda x: x**2 is not given a label. This is because we probably won’t call it again later, it was just something short and simple we needed temporarily.

The fact that lambda functions need not be given a name is the source of another name to describe them: “anonymous functions.”

Also note that lambda-statements are like a function-call in that they return a reference to the function they create. The following is illegal:

apply_to_each(def foo(x): x**2 ,  range(0, 101))

Whereas, apply_to_each(lambda x: x**2 range(0, 101)) is just fine.

So, we use lambda instead of def and _ instead of a long variable name when we want something short, sweet and probably won’t want use again later.

Answered By: IdleCustard
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.