Extreme Python

Logo

Extremely good python content :)

About

Articles

Why not map or filter instead of list comprehensions

by Alan

I prefer using list comprehensions over functions like map and filter for two main reasons:

What about performance though?

The differences are negligible for most use cases and it’s not definitive which approach is faster by the benchmarks I’ve come encountered.

Examples

While I’m biased, I think it’s also important for you to make up your own mind. Here are some side by side comparisons with code:

List of squares

With map:

>>> list(map(lambda x: x * x, numbers))
[1, 4, 9]

With list comprehension:

>>> [i * i for i in numbers]
[1, 4, 9]

List of even numbers

With map:

>>> list(filter(lambda x: x % 2 == 0, numbers))
[2]

With list comprehension:

>>> [i for i in numbers if i % 2 == 0]
[2]

List of squares of even numbers

With map and filter:

>>> list(map(lambda x: x * x, filter(lambda x: x % 2 == 0, numbers)))
[4]

With list comprehension:

>>> [i * i for i in numbers if i % 2 == 0]
[4]
tags: