Syntax
map(function, iterable)\nfilter(function, iterable)Examples
Using map()
Applying a transformation to every item in an iterable.
numbers = [1, 2, 3, 4, 5]
doubled = map(lambda n: n * 2, numbers)
print(list(doubled)) # [2, 4, 6, 8, 10]
# map() also works with named functions
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
temps_c = [0, 20, 37, 100]
temps_f = list(map(celsius_to_fahrenheit, temps_c))
print(temps_f) # [32.0, 68.0, 98.6, 212.0]Using filter()
Keeping only items that satisfy a condition.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = filter(lambda n: n % 2 == 0, numbers)
print(list(evens)) # [2, 4, 6, 8, 10]
words = ["hi", "hello", "hey", "greetings"]
long_words = list(filter(lambda w: len(w) > 3, words))
print(long_words) # ['hello', 'greetings']Combining map() and filter()
Chaining the two together to filter, then transform (or vice versa).
numbers = range(1, 11)
evens = filter(lambda n: n % 2 == 0, numbers)
squared_evens = map(lambda n: n ** 2, evens)
print(list(squared_evens)) # [4, 16, 36, 64, 100]List Comprehension Equivalent
The same logic expressed with a list comprehension, which many developers find more readable.
numbers = range(1, 11)
# map + filter combined
result1 = list(map(lambda n: n ** 2, filter(lambda n: n % 2 == 0, numbers)))
# Equivalent, often more readable, list comprehension
result2 = [n ** 2 for n in numbers if n % 2 == 0]
print(result1 == result2) # TrueBest practices
- Consider a list comprehension instead of map()/filter() with a lambda - it is often more readable in Python, though both are valid
- Remember map() and filter() return lazy iterator objects, not lists - wrap with list() if you need to see or index the results directly
- Use map() with a named function (not just a lambda) when the transformation logic is complex or reused elsewhere
- Chain filter() before map() when you need to both narrow down and transform a collection
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference