4 ms·
I never understood why python had lambda and map when list comprehension does exactly the same thing in a pythonic way. I mean, we don't ask Haskell to adopt li
by wodenokoto 12y ago
I never understood why python had lambda and map when list comprehension does exactly the same thing in a pythonic way. I mean, we don't ask Haskell to adopt list comprehension.
I mean, what do you gain from
map(lambda x: a*x, s)
over
[a*x for x in s]?
But as far as I can understand this article, map and lambda are earlier than list comprehension. Is that true?
- lgas 12y agoExcept that Python's listen comprehension syntax was inspired directly by Haskell's.
- wodenokoto 12y agoReally? Guess I really have my languages screwed up!
- Lambdanaut 12y agoYeah, Python took lambdas from the more lispy languages and it took list comprehensions from Haskell, which in turn took them from Set Theory.
- bennylope 12y agoPython's [list] comprehension syntax was directly inspired by Haskell's list comprehension syntax. And it's also widely (I'd argue) considered to be the Pythonic way of composing lists (and other iterables), rather than using map. It's provenance doesn't detract from that.
- burntsushi 12y agoThose aren't the same in Python 3. $ python3 >>> [2 * x for x in [1, 2, 3]] [2, 4, 6] >>> map(lambda x: 2 * x, [1, 2, 3]) <map object at 0x7f160f535438>
- netheril96 12y agoThen use a generator expression: `(2 * x for x in [1, 2, 3])` This is functionally (pun intended) equivalent to `map(lambda x: 2 * x, [1, 2, 3])`
- lmm 12y agomap and lambda predate list comprehensions, yes. It's useful to have map as a first-class function that you can pass to another function: def operate_on_two_things(hof): return (hof([1, 2, 3], lambda x: x + 1), hof(("A", "B"), lambda y: y + "A"))) operate_on_two_things(map) (trivial example, but it hopefully makes the point - it's harder to do that with a list comprehension)
- js2 12y agomap and related functions such as reduce and filter, along with lambda have been around since python 1.x days (not sure how far back, I started with 1.5.2). Comprehensions were added in Python 2.0.