Using map() and filter()
Published:
• Last updated:
• By Jeferson Peter
Python
Have you ever wanted to transform or filter a list without writing a for loop?
Python gives you two functional tools:map()to apply a function, andfilter()to select items by condition.
Using map()
nums = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, nums))
print(doubled)
# [2, 4, 6, 8]
Using filter()
nums = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)
# [2, 4]
Equivalent with list comprehensions
nums = [1, 2, 3, 4, 5]
doubled = [x * 2 for x in nums]
evens = [x for x in nums if x % 2 == 0]
print(doubled)
print(evens)
# [2, 4, 6, 8, 10]
# [2, 4]
Conclusion
map()transforms items.filter()keeps items matching a condition.- List comprehensions often make code more Pythonic, but
map()andfilter()remain powerful tools.