Filter () function in Python

How is the filter () function syntax, what parameters and how does it work? Invites you to read the track.

Python's filter () function filters out elements according to the condition of the function func from list, dict . This function will only return the values ​​that the condition in the func accepts (ie True). How is the filter () function syntax, what parameters and how does it work? Invites you to read the track.

Syntax of filter () function in Python

 filter(func, iterable) 

Parameters of filter function ()

The filter () function has 2 parameters:

  1. func: is a conditional function to check whether the elements in interable are true or false, func can only return True or False.
  2. interable: is iterable to filter, can be set, list, tuple or container.

Example: How does the filter () function work?

 # danh sách chữ cái 
alphabet = ['a', 'b', 'd', 'e', 'i', 'j', 'o']

# lọc nguyên âm
# viết bởi TipsMake.com
def filterNguyenam(alphabet):
nguyenam = ['a', 'e', 'i', 'o', 'u']

if(alphabet in nguyenam):
return True
else:
return False

filterNguyenam = filter(filterNguyenam, alphabet)

print('Các nguyên âm được lọc là:')
for nguyenam in filterNguyenam:
print(nguyenam)

Run the program, the result is:

 Các nguyên âm được lọc là: 
a
e
i
o

Here, we list a list of letters and need to filter out vowels in it.

You can use a for loop to test each component in the list and store it to another list, but using Python the process will be easier and faster by using the filter method (). .

Example 2: filter () works without func.

 # random list 
# viết bởi TipsMake.com
randomList = [1, 'a', 0, False, True, '0']

filteredList = filter(None, randomList)

print('Các phần tử được lọc là:')
for element in filteredList:
print(element)

Run the program, the result is:

 Các phần tử được lọc là: 
1
a
True
0

Here, we have a random list of numbers, strings and boolean called randomList. We pass randomList to the filter () function with the first parameter (func) being None. At this point, the function itself becomes Identity function by default, so we get TRUE elements 1, a, True and '0' ('0' in string form).

Previous article: Function hasattr () in Python

Next lesson: int () function in Python

5 ★ | 1 Vote