Filter vs Map in Python: Differences and Real Examples | Pybeginners

Filter vs Map in Python: Differences and Real Examples


When working with collections in Python, two essential built-in functions, filter() and map(), play a major role in data transformation and selection. Understanding their differences will help you write more efficient, cleaner, and more readable code.

What is filter()?

The filter() function filters elements from an iterable based on a condition.

Syntax:

filter(function, iterable)
  • function: Returns True or False for each element.

  • iterable: A list, tuple, set, etc.

It returns a filter object (convertible to list, tuple, etc.).

Example: Filtering Even Numbers

nums = [-4, 5, 9, 1, 3]
even_numbers = list(filter(lambda num: num % 2 == 0, nums))
print(even_numbers)  # Output: [-4]

What is map()?

The map() function transforms elements of an iterable by applying a function to each item.

Syntax:

map(function, iterable)
  • function: Transforms each element.

  • iterable: A list, tuple, set, etc.

It returns a map object (convertible to list, tuple, etc.).

Example: Doubling Numbers

nums = [-4, 5, 9, 1, 3]
doubled_numbers = list(map(lambda num: num * 2, nums))
print(doubled_numbers)  # Output: [-8, 10, 18, 2, 6]

Key Differences Between filter() and map()

Feature filter() map()
Purpose Select elements based on a condition Transform all elements
Output Subset of input elements Same number of elements as input
Function Should return True or False Should return a modified value

More Practical Use Cases

1. Filtering Positive Numbers

nums = [-4, -2, 0, 3, 7, 8]
positives = list(filter(lambda x: x > 0, nums))
print(positives)  # Output: [3, 7, 8]

2. Capitalizing Strings

names = ["alice", "bob", "carol"]
capitalized = list(map(str.capitalize, names))
print(capitalized)  # Output: ['Alice', 'Bob', 'Carol']

3. Combining filter() and map()

First filter, then transform:

nums = range(-10, 11)
positive_squares = list(map(lambda x: x ** 2, filter(lambda x: x > 0, nums)))
print(positive_squares)  # Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

4. Filtering Non-Empty Strings

words = ["hello", "", "world", " ", "python"]
non_empty = list(filter(lambda word: word.strip(), words))
print(non_empty)  # Output: ['hello', 'world', 'python']

When to Use Which?

  • Use filter() when you need to select items matching a specific condition.

  • Use map() when you need to transform or modify every element in an iterable.

You can also chain map() and filter() for more complex pipelines!

Conclusion

Both filter() and map() are indispensable tools for writing clean, efficient, and Pythonic code. Learning when and how to use them will greatly improve your coding style and make your programs more elegant.

🌟 Quick Tip: In modern Python, list comprehensions often replace filter() and map() for simple cases, but knowing them gives you more flexibility and better functional programming skills!

You are not logged in yet, please login or sign up to comment
    0 people participated | 0 comments
    No comments yet, feel free to start the conversation!