Skip to content
Foxipa

Suggest an edit

Tell us what should be corrected, clarified, or improved. Submission will be connected to Foxipa’s contribution service later.

No information is sent anywhere yet. Your suggestion is only prepared in your browser.

Learning

Python map and filter

Learn Python's map and filter built-ins for lazy transformation and selection of iterable values.

Levels: Beginner ~12 min read

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.

Interactive Runnable example
Edit

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.

Interactive Runnable example
Edit

Ready to run.

Filter items with a test

Pass a function and an iterable to filter. The function decides which original items remain.

Interactive Runnable example
Edit

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.

Interactive Runnable example
Edit

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.

Interactive Runnable example
Edit

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.

Interactive Runnable example
Edit

Ready to run.

Was this page helpful?

Mark this learning resource complete to track your learning progress.