Member-only story

Python Tips — How to Write Better Functions, Part Three

Tony
4 min readJan 8, 2024

Prefer Python Comprehensions Over map and filter Functions

Comprehensions in Python provide a more concise and readable way to create new sequences (like lists, sets, dictionaries) from existing ones, compared to using functions like map and filter. For example, suppose we have a list of numbers and we want to create a new list containing the squares of these numbers. Here’s how you might do it with map:

numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))

And here’s how we can achieve the same result with a list comprehension:

numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]

As you can see, the list comprehension version is more readable and straightforward. Similarly, suppose we want to filter the list to only include the numbers that are greater than 2. Here’s how you might do it with filter:

numbers = [1, 2, 3, 4, 5]
greater_than_two = list(filter(lambda x: x > 2, numbers))

And here’s the equivalent list comprehension:

numbers = [1, 2, 3, 4, 5]
greater_than_two = [x for x in numbers if x > 2]

Again, the list comprehension is cleaner and easier to understand. Thus, it’s…

--

--

Tony
Tony

No responses yet