- If, Else и Elif в лямбда-функциях в Python
- Синтаксис
- Использование if-else в лямбда-функции
- Условная лямбда-функция Python без if-else
- Python : How to use if, else & elif in Lambda Functions
- Using if else in Lambda function
- Frequently Asked:
- Creating conditional lambda function without if else
- Using filter() function with a conditional lambda function (with if else)
- Using if, elif & else in a lambda function
- Related posts:
- Share your love
- Leave a Comment Cancel Reply
- Terms of Use
- Disclaimer
- Is there a way to perform "if" in python's lambda? [duplicate]
- 16 Answers 16
If, Else и Elif в лямбда-функциях в Python
Лямбда-функция Python — это функция, которая определена без имени. Вместо этого анонимные функции определяются с помощью ключевого слова lambda. В этой статье мы обсудим, как использовать if, else if и else в лямбда-функциях в Python.
Синтаксис
Лямбда-функции могут иметь любое количество параметров, но только одно выражение. Это выражение оценивается и возвращается. Таким образом, лямбда-функции можно использовать везде, где требуются функциональные объекты.
См. следующий пример функции Lambda в Python.
Использование if-else в лямбда-функции
Синтаксис if-else в лямбда-функции следующий.
Например, давайте создадим лямбда-функцию, чтобы проверить, находится ли заданное значение в диапазоне от 11 до 22.
- 15 находится между 11 и 22, поэтому возвращается True.
- 22 не меньше 22. Поэтому возвращается False.
- 21 находится между 11 и 22. Таким образом, он возвращает True.
Условная лямбда-функция Python без if-else
Мы можем избежать использования ключевых слов if & else и при этом добиться тех же результатов. Например, давайте изменим созданную выше лямбда-функцию, удалив ключевые слова if-else.
Мы получили тот же результат, и вы можете видеть, что мы можем написать условия без операторов if-else.
Лямбда-функция делает то же самое, что и выше, проверяет, находится ли заданное число в диапазоне от 10 до 20. Теперь давайте используем эту функцию для проверки некоторых значений.
Python : How to use if, else & elif in Lambda Functions
In this article we will discuss how to use if , else if and else in a lambda functions in Python. Will also explain how to use conditional lambda function with filter() in python.
Using if else in Lambda function
Using if else in lambda function is little tricky, the syntax is as follows,
For example let’s create a lambda function to check if given value is between 10 to 20 i.e.
lambda x : True if (x > 10 and x < 20) else False
Here we are using if else in a lambda function, if given value is between 10 to 20 then it will return True else it will return False. Now let’s use this function to check some values i.e.
# Lambda function to check if a given vaue is from 10 to 20. test = lambda x : True if (x > 10 and x < 20) else False # Check if given numbers are in range using lambda function print(test(12)) print(test(3)) print(test(24))
Frequently Asked:
Creating conditional lambda function without if else
Well using ‘if’ ‘else’ keywords makes things easy to understand, but in lambda we can avoid using if & else keywords and still achieve same results. For example let’s modify the above created lambda function by removing if else keywords & also True False i.e.
This lambda function does the same stuff as above i..e checks if given number lies between 10 to 20. Now let’s use this function to check some values i.e.
# Lambda function to check if a given vaue is from 10 to 20. check = lambda x : x > 10 and x < 20 # Check if given numbers are in range using lambda function print(check(12)) print(check(3)) print(check(24))
Using filter() function with a conditional lambda function (with if else)
filter() function accepts a callback() function and a list of elements. It iterates over all elements in list and calls the given callback() function
on each element. If callback() returns True then it appends that element in the new list. In the end it returns a new list of filtered elements only.
# List of numbers listofNum = [1,3,33,12,34,56,11,19,21,34,15]
Now let’s use filter() function to filter numbers between 10 to 20 only by passing a conditional lambda function (with if else) to it i.e.
# Filter list of numbers by keeping numbers from 10 to 20 in the list only listofNum = list(filter(lambda x : x > 10 and x < 20, listofNum)) print('Filtered List : ', listofNum)
Filtered List : [12, 11, 19, 15]
it uses the passed lambda function to filter elements and in the end returns list of elements that lies between 10 to 20,
Using if, elif & else in a lambda function
Till now we have seen how to use if else in a lambda function but there might be cases when we need to check multiple conditions in a lambda function. Like we need to use if , else if & else in a lambda function. We can not directly use elseif in a lambda function. But we can achieve the same effect using if else & brackets i.e.
Create a lambda function that accepts a number and returns a new number based on this logic,
- If the given value is less than 10 then return by multiplying it by 2
- else if it’s between 10 to 20 then return multiplying it by 3
- else returns the same un-modified value
# Lambda function with if, elif & else i.e. # If the given value is less than 10 then Multiplies it by 2 # else if it's between 10 to 20 the multiplies it by 3 # else returns the unmodified same value converter = lambda x : x*2 if x < 10 else (x*3 if x < 20 else x)
Let’s use this lambda function,
print('convert 5 to : ', converter(5)) print('convert 13 to : ', converter(13)) print('convert 23 to : ', converter(23))
convert 5 to : 10 convert 13 to : 39 convert 23 to : 23
Complete example is as follows,
def main(): print('*** Using if else in Lambda function ***') # Lambda function to check if a given vaue is from 10 to 20. test = lambda x : True if (x > 10 and x < 20) else False # Check if given numbers are in range using lambda function print(test(12)) print(test(3)) print(test(24)) print('*** Creating conditional lambda function without if else ***') # Lambda function to check if a given vaue is from 10 to 20. check = lambda x : x >10 and x < 20 # Check if given numbers are in range using lambda function print(check(12)) print(check(3)) print(check(24)) print('*** Using filter() function with a conditional lambda function (with if else) ***') # List of numbers listofNum = [1,3,33,12,34,56,11,19,21,34,15] print('Original List : ', listofNum) # Filter list of numbers by keeping numbers from 10 to 20 in the list only listofNum = list(filter(lambda x : x >10 and x < 20, listofNum)) print('Filtered List : ', listofNum) print('*** Using if, elif & else in Lambda function ***') # Lambda function with if, elif & else i.e. # If the given value is less than 10 then Multiplies it by 2 # else if it's between 10 to 20 the multiplies it by 3 # else returns the unmodified same value converter = lambda x : x*2 if x < 10 else (x*3 if x < 20 else x) print('convert 5 to : ', converter(5)) print('convert 13 to : ', converter(13)) print('convert 23 to : ', converter(23)) if __name__ == '__main__': main()
*** Using if else in Lambda function *** True False False *** Creating conditional lambda function without if else *** True False False *** Using filter() function with a conditional lambda function (with if else) *** Original List : [1, 3, 33, 12, 34, 56, 11, 19, 21, 34, 15] Filtered List : [12, 11, 19, 15] *** Using if, elif & else in Lambda function *** convert 5 to : 10 convert 13 to : 39 convert 23 to : 23
Related posts:
Share your love
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Is there a way to perform "if" in python's lambda? [duplicate]
You can't print or raise in a lambda. Lambdas are just functions, you can alwaya use a function instead.
I disagree with you. I need 4 different, very short functions like the one above that need to be put in a list/dictionary so I can iterate over them and select which ones to use in each iteration. Instead of many lines of code of just inits, before the iteration, itself I can bring it down to only 4 lines of init code. The less the merrier..
4 lines of code is not a laudable solution when other people have to read, interpret, understand and maintain the code. Further, the "print/raise" problem in the example shows this which cannot and should not be done in lambdas.
@LennartRegebro lambdas are not functions in python, they are only expressions, that is why there are many things you can not do with them.
@AaronMcMillin Lambdas are functions. They are restricted to expressions for syntax reasons, but they ARE functions.
16 Answers 16
The syntax you're looking for:
lambda x: True if x % 2 == 0 else False
But you can't use print or raise in a lambda.
It's a horrible syntax--easily the worst Python language construct, approaching Perl levels of absurdity in its out-of-order evaluation--but it's what was asked for. You're seriously voting down answers for being correct?
@Glenn Maynard: it's not the syntax that horrifying. It's any expression of the form True if expression else False . The if construct is totally redundant and therefore deeply and horrifyingly confusing. It's as bad as the statement form: if expression: return True .
It's the correct answer to the question "How do I write a lambda function that tells me if a number is even?" It is not, however, a correct answer to the question that the OP originally asked. However much you don't like the example I contrived, my post does, in fact, clearly answer the OP's question.
It's painfully obvious that anyone suggesting "x%2==0"--or voting up a comment recommending it, which makes at least seven people--didn't even read the original question.
why don't you just define a function?
def f(x): if x == 2: print(x) else: raise ValueError
there really is no justification to use lambda in this case.
@Glenn Maynard: There's almost no reason to use a lambda, period. Assigning a lambda to a variable -- as a stand-in for def -- is generally a Very Bad Idea (tm). Just use a def so mere mortal programmers can read, interpret, understand and maintain it.
There are plenty of legitimate uses of lambdas. If you can't think of any, then that's not lambda's fault. (I'm not a fan of the syntax itself, of course--it's a clumsy workaround for the fact that Python's poorly-conceived indentation syntax can't handle inline functions like normal languages.)
Probably the worst python line I've written so far:
f = lambda x: sys.stdout.write(["2\n",][2*(x==2)-2])
You can easily raise an exception in a lambda, if that's what you really want to do.
def Raise(exception): raise exception x = lambda y: 1 if y < 2 else Raise(ValueError("invalid value"))
Is this a good idea? My instinct in general is to leave the error reporting out of lambdas; let it have a value of None and raise the error in the caller. I don't think this is inherently evil, though--I consider the "y if x else z" syntax itself worse--just make sure you're not trying to stuff too much into a lambda body.