SyntaxStudy
Sign Up
Home Python Reference map() / filter()

map() / filter()

function

map() applies a function to each item; filter() keeps items where the function returns True.

Syntax

map(function, iterable) filter(function, iterable)

Example

python
numbers = [1, 2, 3, 4, 5, 6]

# map
squares = list(map(lambda x: x**2, numbers))
print(squares)  # [1, 4, 9, 16, 25, 36]

# filter
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4, 6]

# List comprehension (preferred Pythonic alternative)
evens2 = [x for x in numbers if x % 2 == 0]