Storing Filtered Data in a Tuple
In this lesson, you’ll see how you can ensure that your filtered down data is safely stored in a tuple, which is an immutable data structure. You’ll use the
tuple() function and wrap it around
filter(). Now you have all of the elements generated by this iterator stored inside a tuple.
Then you’ll walk through another quick example to review how you can use
filter() to see which items in your data set meet specific criteria. You’ll be using
lambda expressions again.
Prize scientists. The
filter() function is pretty cool because it allows you to apply a function over a whole list of things, or an iterable of things, and then every item in this list, or in this iterable, gets passed to the function—in this case, it would be
x—and then we can make a decision and return
False. And if we return
True, this item will be included in the resulting list, in a filtered list, and if we return
False it will not be included.
Okay, so what I’m doing here is I’ve defined this expression here that would actually convert it to a tuple and then print it out so it looks nice and clean, and I didn’t yet add the
filter() function, which we’re going to do now. In this case, you know, I could just always return
So, if the
filter() function would always return
True, then we are just going to return the whole list, right? And you can filter on anything you want, right? I could say, okay, if
x.field == 'physics', we’re only going to get people that worked in physics.
x.field == 'physics' and x.nobel—let’s actually use the short version this time,
x.nobel—then I get a tuple of length
1, because that’s the only person. Marie Curry, here, is the only person that this
filter() expression matched on.
Become a Member to join the conversation.