Topic 36 of 58
map, filter, zip
Overview
These three functions are the pillars of Functional Programming in Python. They allow you to apply transformations or evaluate conditions across entire iterables (like lists) without explicitly writing for loops. Crucially, in Python 3, they are 'lazy'. They return memory-efficient iterator objects rather than full lists. They only compute values one-by-one as requested, making them capable of processing massive data streams without crashing your RAM.
Syntax
python
nums = [1, 2, 3, 4, 5]
# map(function, iterable): Applies a function to every item
squares_iter = map(lambda x: x**2, nums)
print(list(squares_iter)) # [1, 4, 9, 16, 25]
# filter(function, iterable): Keeps only items where the function returns True
evens_iter = filter(lambda x: x % 2 == 0, nums)
print(list(evens_iter)) # [2, 4]
# zip(iter1, iter2): Pairs up elements from multiple iterables sequentially
names = ["Alice", "Bob"]
scores = [95, 88]
paired_iter = zip(names, scores)
print(list(paired_iter)) # [('Alice', 95), ('Bob', 88)]Common Pitfalls
- Forgetting to wrap the results in
list(). Because they return iterators, printingmap(func, data)directly outputs an unreadable memory address like<map object at 0x...>. - Using
zipon iterables of unequal length.zipsilently stops pairing the moment the shortest iterable runs out. If you need to retain the longer data, useitertools.zip_longest.
Interview Questions
Q:
How do you 'unzip' a list of paired tuples back into two separate lists?
A:
By using the unpack operator with zip: names, scores = zip(*paired_list). This reverses the operation.
Real-World Example
Quickly converting two lists of related data into a dictionary.
example
python
keys = ["hostname", "port", "environment"]
values = ["localhost", 5432, "production"]
# zip creates the key-value tuples, dict() casts them instantly
db_config = dict(zip(keys, values))
print(db_config)
# {'hostname': 'localhost', 'port': 5432, 'environment': 'production'}Check Your Knowledge
Test your understanding of map, filter, zip with these quick questions.