3 ms·
How about {list|dict|set} comprehensions? I don't know if they are considered part of functional programming (and the definition of FP seems to be somewhat loos
by vram22 8y ago
How about {list|dict|set} comprehensions? I don't know if they are considered part of functional programming (and the definition of FP seems to be somewhat loose anyway, AFAICT - correct me if I'm wrong, anyone), but they can be nice to use. They can even be nested (never gone beyond 2 levels myself) and if/else clauses can be in them too. E.g.:
>>> def odd(n): return n % 2 == 1
...
>>> [ i if odd(i) else -i for i in range(1, 11) ]
[1, -2, 3, -4, 5, -6, 7, -8, 9, -10]
- cgopalan 8y agoIndeed comprehensions are part of many functional languages like Haskell, Ocaml, Clojure.
- vram22 8y agoGood to know, thanks. In fact, now I think I remember reading that Python got the idea of comprehensions from Haskell.
- ilovecaching 8y agoComprehensions are a key part of functional programming in Python. Python lambdas are fairly awkward to use. Comprehensions provide a better syntax for transforming data in many cases.
- vram22 8y agoYes, lambas don't allow statements in them, only an expression. In [8]: f = lambda x: x * 2 In [9]: f(2) Out[9]: 4 In [10]: g = lambda x: if x % 2 == 0: x * 2 else x * 3 File "<ipython-input-10-f7248669b8fd>", line 1 g = lambda x: if x % 2 == 0: x * 2 else x * 3 ^ SyntaxError: invalid syntax