How to use the Filter function in Python
Table of Contents
Arrays in Python are useful because they can hold several elements of data in a single variable.
However, sometimes we need to create a new array by filtering out values from an existing array.
In this post, we'll learn how to use the filter method in Python to create a new array from an existing array.
How to use the filter method in Python
To start, let's define an example array that we will eventually filter:
PYTHONarray = [23, 14, 65, 42, 7];
This array contains five elements of random numbers.
Now let's say we only want to keep the numbers that are even.
We can use the filter
method and pass it a function that will return True
if the number is even and False
if it is not.
PYTHONarray = [23, 14, 65, 42, 7];
def isEvenNumber(n):
return n % 2 == 0
results = filter(isEvenNumber, array);
print(list(results));
BASH[14, 42]
The filter
method will take each element in the array, and pass it through the function that we provide, and if the function returns True
, it will add the element to the new array, otherwise it will not.
Thus, it checks each number to see if it is even or not, and allows it to pass the filter if it is, and we end up with a new array of just the even numbers.
Alternatively, you can make use of lambdas to accomplish the same task:
PYTHONarray = [23, 14, 65, 42, 7];
results = filter(lambda n: n % 2 == 0, array);
print(list(results));
BASH[14, 42]
All you need to do is define the function that you pass to filter and make it do what you want it to do, and you'll end up with a new array full of only the elements that passed the filter.
Conclusion
In this post, we learned how to use the filter
method in Python to create a new array by filtering elements from an existing array.
Simply create a function to pass to filter
and it will use it to create a filtered array for you.
Thanks for reading!
- Getting Started with TypeScript
- Getting Started with Solid
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- Learn how to use v-model with a custom Vue component
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with Vuex: Managing State in Vue