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.
To start, let's define an example array that we will eventually filter:
array = [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.
array = [23, 14, 65, 42, 7]; def isEvenNumber(n): return n % 2 == 0 results = filter(isEvenNumber, array); print(list(results));
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:
array = [23, 14, 65, 42, 7]; results = filter(lambda n: n % 2 == 0, array); print(list(results));
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.
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!
Leave us a message!