The filter() Function: Overview
In this section, you’ll learn the basics of functional programming in Python and how to use the filter()
function to transform data structures.
You’ll take the example data set represented with an immutable data structure from the previous section. Then you’ll create a filtered down version of the same data using Python’s built-in filter()
function, which is one of the functional programming primitives (or building blocks) available in Python. It’s useful in a number of contexts.
Later in this section, you’ll also see how filter()
relates to list comprehensions and generator expressions in Python, and how using these is arguably more Pythonic than relying on plain filter()
calls.
00:00 Hey there and welcome to the next video in my Functional Programming in Python series. If you missed the first video where I talked about “What is functional programming, anyway?” and how can you represent data in immutable data structures for use in your
00:16
functional programs, then you might want to check out the first part of the series before you watch this video. So, in this video, we’re going to take the next step and we’re going to work with this immutable list of scientists that we created in the previous installment, and we’re going to do some interesting transformations on the scientists in that list, or just on that data set, by working with the filter()
function in Python.
Dan Bader RP Team on March 26, 2020
Good question, Jacques! Since the input data was an ordered table of rows (see lesson #1) I went with a pretty direct translation using a tuple as the top-level data structure.
But a set of named tuples should work just as well, depending on the Python version a set would also retain the order of elements.
kemboirodgers00 on April 27, 2020
Dan really helpful thank you
Levi on Feb. 2, 2021
For anyone wanting to follow along without typing the code in manually:
import collections
Scientist = collections.namedtuple("Scientist", ["name", "field", "born", "nobel"])
scientists = (
Scientist(name="Ada Lovelace", field="math", born=1815, nobel=False),
Scientist(name="Emmy Noether", field="math", born=1882, nobel=False),
Scientist(name="Marie Curie", field="physics", born=1867, nobel=True),
Scientist(name="Tu Youyou", field="chemistry", born=1930, nobel=True),
Scientist(name="Ada Yonath", field="chemistry", born=1939, nobel=True),
Scientist(name="Vera Rubin", field="astronomy", born=1928, nobel=False),
Scientist(name="Sally Ride", field="physics", born=1951, nobel=False),
)
Become a Member to join the conversation.
Jacques Clement on March 26, 2020
Would a set of named tuples have not been more appropriate than a tuple of named tuples in this example? You don’t wanna see duplicates in a data structure like this one, so is set not what would enforce this? Thanks in advance.