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
How to Set Up Cron Jobs in Linux
Best Visual Studio Code Extensions for 2022
How to deploy a MySQL Server using Docker
How to deploy an Express app using Docker
How to deploy a Node app using Docker
Using Puppeteer and Jest for End-to-End Testing
Build a Real-Time Chat App with Node, Express, and Socket.io
Using Push.js to Display Web Browser Notifications
Getting Started with React
Using Axios to Pull Data from a REST API
How To Create a Modal Popup Box with CSS and JavaScript
