89DEVs

Python filter() function

filter() overview

The filter() function extracts elements of an object, based on a function.

filter() even numbers

To filter even numbers, we define a is_even() function and use filter() to extract all even numbers. # filter even number using filter() # define is_even() function def is_even(number): if (number % 2) == 0: return True # filter list and return filtered list myNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] filtered = filter(is_even, myNumbers) print(list(filtered)) The list is filtered using our function. Then the filtered object is turned into a list again and the result is printed. [2, 4, 6, 8, 10]

filter() vowels

A second example demonstrates how to filter vowels in a list of characters. # filter vowels from a list of characters characters = ['a', 1, 'b', 2, 'd', 'e', 'z', 99, 'i', 5.5] # define function to check character for vowels def is_vowel(character): return True if character in ['a', 'e', 'i', 'o', 'u'] else False filtered = list(filter(is_vowel, characters)) print(filtered) The list is filtered for vowels and a list of the filtered vowels is returned. ['a', 'e', 'i']

filter() syntax

The syntax of the filter() function is: filter(function, object)

filter() arguments

The filter() function expects exactly two arguments. If more or less than two arguments are given, a TypeError exception is raised. The first argument is a function that can filter values based on True and False. The second argument is a data structure like a set, list or tuple.

filter() return value

The filter() function returns a type filter. Use dict(), tuple() or list() to return it in the original data structure.

                
        

Summary


Click to jump to section