Lambda with if but without else in Python (original) (raw)
Last Updated : 06 Oct, 2021
In Python, Lambda function is an anonymous function, which means that it is a function without a name. It can have any number of arguments but only one expression, which is evaluated and returned. It must have a return value.
Since a lambda function must have a return value for every valid input, we cannot define it with if but without else as we are not specifying what will we return if the if-condition will be false i.e. its else part.
Let's understand this with a simple example of lambda function to square a number only if it is greater than 0 using if but without else.
Example #1:
Python3 `
Lambda function with if but without else.
square = lambda x : x*x if(x > 0)
print(square(6))
`
Output:
File "/home/2c8c59351e1635b6b026fb3c7fc17c8f.py", line 2 square = lambda x : x*x if(x > 0) ^ SyntaxError: invalid syntax
The above code on execution shows SyntaxError, as we know that a lambda function must return a value and this function returns x*x if x > 0 and it does not specify what will be returned if the value of x is less than or equal to 0.
To correct it, we need to specify what will be returned if the if-condition will be false i.e. we must have to specify its else part.
Let's see the above code with its else part.
Code:
Python3 `
Lambda function with if-else
square = lambda x : x*x if(x > 0) else None
print(square(4))
`
Output:
16
Example #2: The first code is with if but without else then second is with if-else.
Python3 `
Example of lambda function using if without else
mod = lambda x : x if(x >= 0)
print(mod(-1))
`
Output:
File "/home/20b09bdd29e24dfe24c185cd99dfcdfa.py", line 2 mod = lambda x : x if(x >= 0) ^ SyntaxError: invalid syntax
Now, let's see it using if-else.
Python3 `
Example of lambda function using if-else
mod = lambda x : x if(x >= 0) else -x
print(mod(-1))
`
Output:
1
Example #3: The first code is with if but without else then second is with if-else.
Python3 `
Example of lambda function using if without else
max = lambda a, b : x if(a > b)
print(max(1, 2))
`
Output:
File "/home/8cf3856fc13d0ce75edfdd76793bdde4.py", line 2 max = lambda a, b : x if(a > b) ^ SyntaxError: invalid syntax
Now, let's see it using if-else.
Python3 `
Example of lambda function using if-else
max = lambda a, b : a if(a > b) else b
print(max(1, 2)) print(max(10, 2))
`
Output:
2 10
Similar Reads
- Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test 9 min read
- Python List Exercise List OperationsAccess List ItemChange List itemReplace Values in a List in PythonAppend Items to a listInsert Items to a listExtend Items to a listRemove Item from a listClear entire listBasic List programsMaximum of two numbersWays to find length of listMinimum of two numbersTo interchange first an 3 min read
- Python String Exercise Basic String ProgramsCheck whether the string is Symmetrical or PalindromeFind length of StringReverse words in a given StringRemove i’th character from stringAvoid Spaces in string lengthPrint even length words in a stringUppercase Half StringCapitalize the first and last character of each word in 4 min read
- Python Tuple Exercise Basic Tuple ProgramsPython program to Find the size of a TuplePython – Maximum and Minimum K elements in TupleCreate a list of tuples from given list having number and its cube in each tuplePython – Adding Tuple to List and vice – versaPython – Sum of tuple elementsPython – Modulo of tuple elementsP 3 min read
- Python Dictionary Exercise Basic Dictionary ProgramsPython | Sort Python Dictionaries by Key or ValueHandling missing keys in Python dictionariesPython dictionary with keys having multiple inputsPython program to find the sum of all items in a dictionaryPython program to find the size of a DictionaryWays to sort list of dicti 3 min read
- Python Set Exercise Basic Set ProgramsFind the size of a Set in PythonIterate over a set in PythonPython - Maximum and Minimum in a SetPython - Remove items from SetPython - Check if two lists have at-least one element commonPython program to find common elements in three lists using setsPython - Find missing and addit 2 min read