Map vs list comprehension

They are not quite the same. For example, with list comprehension you can additionally filter elements:

[x for x in 1:10 if x % 2 == 0]

But map may be shorter and more convenient, e.g.:

[f(input) for input in inputs]
map(f, inputs)

In addition, map (mostly) preserves type of a collection, while list comprehencion doesn’t. Compare:

map(x -> x + 1, Set([1, 2, 3]))
[x + 1 for x in Set([1, 2, 3])]
12 Likes