IT Tricks

The filter () function in Python


The filter () function in Python filters out the conditional elements of the func function from list, dict … This function will only return the values ​​that the condition in func accepts (meaning True). What is the syntax of the filter () function, what parameters and how do it use it? Invites you to read the track.

The syntax of the filter () function in Python

filter(func, iterable)

Parameters of the filter () function

The filter () function has 2 parameters:

  • func: is a conditional function for testing internal elements interable is true or false, func can only return True or False.
  • interable: are 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 Quantrimang.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)

Running the program, the result is returned:

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 the vowels in it.

You can use the for loop to check each element of the list and store it into 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 Quantrimang.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)

Running the program, the result is returned:

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

Here, we have a random list of numbers, strings and booleans called randomList. We pass randomList into the filter () function with the first parameter (func) of None. At this point, the function itself becomes the Identity function by default, so we get TRUE elements 1, a, True and ‘0’ (‘0’ as strings).

Previous lesson: The hasattr () function in Python

Next article: The int () function in Python

.

Leave a Reply

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