Python has a lot of powerful features that make it one of the most popular programming languages. One such feature is the list, which stores and manipulates data in lists with elements indexed by consecutive integers (e.g., 0, 1, 2). List objects are versatile and can be used to filter items from a list or to iterate over its contents.
Lists are often used as parameters for other functions that need them to store information so they don’t have to manage their own storage space. In this blog post we will show you how Python’s built-in list methods let you filter string elements from a list using simple code examples.
Python lists are mutable, which means they can be changed by updating values inside them. You cannot change any other data type like this because they aren’t mutable.
Filtering a List in Python is s a process of finding items that belong to the list and removing or hiding all other elements from it. The result is a new List with only those filtered items in it.
Python filter() function
filter() is a powerful Python method that can be used to create more concise and easier-to-read code. Check out this blog post for tips on how you might use the filter() function in your own projects!
The filter() method filters the given sequence with a function that tests each element in the sequence. It returns an iterator that is already filtered.
The filter() function looks through the whole list and applies a function to each one. When the function returns True, the element was added to returned list.
The example below filter odd ages from a list of given ages:
ages = [21, 22, 23, 24, 25, 26, 27, 28] odd_ages = filter(lambda age: age % 2, ages) print(list(odd_ages)) #output: [21, 23, 25, 27]
The function we passed as the first parameter returns any element that is divided by 2 and return 1 (which is true). The filter() function returns an iterator. You can use a for loop to iterate over it. Or you can use the list() function to convert the iterator to a list.
Let’s view another example with tuples. In this one, we need to filter a list of employees who earn equal or more than 3000.
salaries = [ ['Adam', 2000], ['Peter', 3500], ['Max', 3000], ['Mary', 3200], ['John', 2900], ['Newton', 3000], ] high_salaries = filter(lambda employee: employee >= 3000, salaries) print(list(high_salaries)) #output: [['Peter', 3500],['Max', 3000],['Mary', 3200],['Newton', 3000]]