5 ms·
Like others have said: - Can only have one line - Can only use expressions, not statements. E.g. `print`s, loops, conditionals are out. - Overall just kinda
by rustyminnow 6y ago
Like others have said:
- Can only have one line
- Can only use expressions, not statements. E.g. `print`s, loops, conditionals are out.
- Overall just kinda clunky
Here's an SO post about lambdas where the answer is "Use def instead."
https://stackoverflow.com/questions/14843777/how-to-write-python-lambda-with-multiple-lines https://stackoverflow.com/questions/14843777/how-to-write-py...
- bobbylarrybobby 6y agoThe lambda calculus is Turing complete, so in theory, Python’s lambdas should suffice...
- rustyminnow 6y agoI mean... You're right. They suffice. They're just less friendly (i.e. useful) than lambdas in other languages.
- zelphirkalt 6y agoWhich of course says nothing about usability and readability.
- jolux 6y agoTuring completeness is completely unrelated to whether or not anonymous functions are easy to use in Python.
- heavyset_go 6y agoprint() is a function now and you can use it with lambdas.
- pmiller2 6y agoEven in Python 2, you can do something like this: println = lambda s: sys.stdout.write(s + '\n') Not that it really makes things much better, but, at least it shows you can do it.
- seertaak 6y agoExactly. Kind of an own-goal too, from none other than ex-BDFL. While not totally obvious, it's not impossible to widen the syntax to allow multi-line lambdas, you just need to ditch the stack-based lexer-integrated whitespace sensitivity behaviour.
- diarrhea 6y agoThis works for conditionals: In [4]: f = lambda x: "Yes" if x else "No" In [5]: f(True) Out[5]: 'Yes' In [6]: f(False) Out[6]: 'No' It's Python's version of ternary operators, so not sure if that counts as a "true" conditional; but it is one. Loops don't work, but list comprehensions do, and they are definitely the way to go here. Multi-line loops deserve a `def`.
- dragonwriter 6y ago> Can only use expressions, not statements. E.g. `print`s, loops, conditionals are out. print is a function (and thus can be used in expressions) python has conditional expressions (<true-val> if <cond> else <false-val>) loops are a limitation, though comprehensions, map(), functools.reduce(), and the itertools module can allow lots of looping functionality in an expression.