Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of OR operator in python lambda function

Tags:

python

lambda

There is a code example in the O Reilly Programming Python book which uses an OR operator in a lambda function. The text states that "[the code] uses an or operator to force two expressions to be run".

How and why does this work?

widget = Button(None, # but contains just an expression
text='Hello event world',
command=(lambda: print('Hello lambda world') or sys.exit()) )
widget.pack()
widget.mainloop()
like image 965
czolbe Avatar asked Jun 02 '17 04:06

czolbe


People also ask

What is use of lambda function in Python?

We use lambda functions when we require a nameless function for a short period of time. In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter() , map() etc.

How is lambda () function called?

In Python, a lambda function is a single-line function declared with no name, which can have any number of arguments, but it can only have one expression. Such a function is capable of behaving similarly to a regular function declared using the Python's def keyword.

Which is the correct syntax for lambda in Python?

The syntax of a lambda function is lambda args: expression . You first write the word lambda , then a single space, then a comma separated list of all the arguments, followed by a colon, and then the expression that is the body of the function.

What does lambda X X do?

The whole lambda function lambda x : x * x is assigned to a variable square in order to call it like a named function. The variable name becomes the function name so that We can call it as a regular function, as shown below. The expression does not need to always return a value.


2 Answers

Every funnction in Python returns a value. If there is no explicit return statement it returns None. None as boolean expression evaluates to False. Thus, print returns None, and the right hand side of the or expression is always evaluated.

like image 132
clemens Avatar answered Nov 15 '22 00:11

clemens


The Boolean or operator returns the first occurring truthy value by evaluating candidates in sequence from left to right. So in your case, it is used to first print 'Hello lambda world' since that returns None (considered falsey), it will then evaluate sys.exit() which ends your program.

lambda: print('Hello lambda world') or sys.exit()

Python Documentation:

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

like image 31
Taku Avatar answered Nov 15 '22 00:11

Taku