Python map and filter
Learn Python's map and filter built-ins for lazy transformation and selection of iterable values.
Basic
Python's
map and
filter built-ins both work with iterables, but they answer different questions.
map transforms each item, while
filter keeps only items that pass a test.
Transform every item with map
Pass a function and an iterable to
map. The result is an iterator that yields the function result for each input item.
Output
Ready to run.
The function receives one item at a time and its return value becomes the corresponding item in the mapped result.
Map several iterables together
When
map receives more than one iterable, the function receives one item from each iterable at the same position.
Output
Ready to run.
Filter items with a test
Pass a function and an iterable to
filter. The function decides which original items remain.
Output
Ready to run.
Unlike
map,
filter does not replace an item with the function's return value. A truthy result keeps the original item.
Filter by truth value
When the function argument is
None,
filter uses the truth value of each item and removes the false ones.
Output
Ready to run.
Remember that both results are iterators
Both built-ins return iterators. Iterating over the result consumes it, so a second pass over the same result produces no more values.
Output
Ready to run.
Choose the operation that matches the intent
Use
map when every item should become a new value. Use
filter when some original items should be kept and others discarded.
Output
Ready to run.
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.