+ 1

Can python lambda contain the statement?

Simply speaking notation of f = lambda : x * x for x in range(10). I have read that python is not a strict language, so that we can include additional if- statement or for clause there. You can refer to Deitel Python book which cover data science and AI for higher version.

4th Nov 2024, 2:33 AM
Oliver Pasaribu
Oliver Pasaribu - avatar
4 ответов
+ 4
your lambda cannot be parsed perhaps you mean f = lambda n: (x*x for x in range(n)) # f returns a generator expression, which can be unpacked by * print(*f(5)) # if-else can be used in lambda f = lambda n: (x*x if x%2==0 else x*x*x for x in range(n)) print(*f(20), sep='\n')
4th Nov 2024, 3:47 AM
Bob_Li
Bob_Li - avatar
+ 1
RuntimeTerror You are limited to one expression. True, you can make it long and complicated with multiple if else or by nesting other lambda inside it, but eventually it still have to be in one long expression and you often end up with code that is hard to read. Nice for flexing coding skill, but not on production code It's better to use a regular functions for complicated cases.
5th Nov 2024, 2:23 AM
Bob_Li
Bob_Li - avatar
+ 1
In most cases, long and complicated are not directly proportional in python. If I'm correct, I think I've seen some of the python's source code using a long lambda expression themselves and calling the function on the same line by assigning the walrus operator to it. Regardless, it was easier to read. It's been very long since I used python, I rarely remember the zen and especially with the recent update, I may be wrong about somethings
5th Nov 2024, 3:48 AM
RuntimeTerror
RuntimeTerror - avatar
</