125

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.

msouth
  • 832
  • 11
  • 21
laycat
  • 5,381
  • 7
  • 31
  • 46
  • 27
    For those that what a parameterless lambda, the syntax is `lambda : True` – Robino Mar 14 '18 at 21:32
  • 2
    @ToothpickAnemone great reply! i mostly use lambda with no variables for initialising defaultdicts these days. hope its useful to people reading this thread. ht = {} ht = defaultdict(lambda:0, ht) – laycat Apr 23 '18 at 16:03
  • 2
    Possible duplicate of [What is the purpose of the single underscore "\_" variable in Python?](https://stackoverflow.com/questions/5893163/what-is-the-purpose-of-the-single-underscore-variable-in-python) – Billal Begueradj Aug 07 '19 at 12:06
  • 1
    @Robino why `lambda : True` instead of `lambda: True`? Is this extra space supposed to indicate something? Just like the way it looks? – Marshall Eubanks May 18 '23 at 20:55
  • @MarshallEubanks it distinguishes it from other colon usecases, such as fucn def. You certainly need the space after it. Be consistent, whatever you choose. – Robino May 23 '23 at 14:59

6 Answers6

229

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
winklerrr
  • 13,026
  • 8
  • 71
  • 88
  • 7
    @dopatraman tested it with `Python 3.6.2` under `Mac OS 10.12` and it works. – winklerrr Sep 10 '17 at 14:44
  • 8
    Maybe you could add the information that the variable name `_` is commonly used when the variable itself isn't really needed. It's like a "throw-away-variable", just a placeholder which is of no use. – winklerrr Sep 10 '17 at 14:44
  • 2
    @dopatraman In Ipython, _ holds value returned by the last expression. I avoid using _ for this reason. https://stackoverflow.com/questions/17580289/assigning-a-value-to-single-underscore-in-python-ipython-interpreter – Taro Kiritani Mar 19 '18 at 06:01
10

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.

Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
  • not only python conversion, it's a language-agnostic and underscore is used to indicate that a variable is temporary or insignificant – Sławomir Lenart Jan 15 '19 at 13:54
7

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.

Community
  • 1
  • 1
miku
  • 181,842
  • 47
  • 306
  • 310
7

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.

Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42
5

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

hyades
  • 3,110
  • 1
  • 17
  • 36
3

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
haccks
  • 104,019
  • 25
  • 176
  • 264