How To Filter Python List, Dictionary, Array, String List, Object Tutorial with Examples? – POFTUT

How To Filter Python List, Dictionary, Array, String List, Object Tutorial with Examples?

Python programming language provides filter() function in order to filter given array, list, dictionary or similar iterable struct.  filter() function can be used to create iterable by filtering some elements of the given data.

Syntax

filter() function has following syntax. FUNCTION is the function name we will use to test given dataset and create a new iterable list. ITERABLE is the data we will check with our function and filter.

Filter List

The most popular usage of the filter() function is using Python List. We will provide a list which will be filtered with the given function. In this example, we will provide the list named numbers  and use oddF'lter() function in order to filter numbers.

Filter List

Filter List

We will provide the list named numbers. This list contains numbers from 1 to the 9. We will create filter function named oddFilter() which will filter for odd numbers in the given list and return True if the given element is odd or return False if the given element is even. Then we will add odd numbers to a new list named  odd_numbers.

Filter Dictionary

Dictionaries can be also filtered with the filter() function. We can filter dictionaries according to their key or value for each element. In this example, we will filter the dictionary named names.

Filter Dictionary

Filter Dictionary

Filter String List

We can also use filter() function in order to filter given string list. In this example, we will look for strings which contains i letter.

Filter String List

Filter String List

Filter Using Lambda

Lambda is very useful when we want not to use a function. As  filter() function requires a function we can skip defining a new function and use lambda like a function. We will filter those strings which contain the letter i.

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)