How to use Filter in python basic tutorial

  • 2020-05-19 05:11:32
  • OfStack

python Filter

The built-in function filter() in Python is primarily used to filter sequences.

Like map, filter() receives a function and a sequence, but unlike map(), filter() applies the incoming function to each element in turn, and then returns a value of

True or False decides whether to keep or discard the element.

Case 1:


number_list = range(-5, 5) 
less_than_zero = list(filter(lambda x: x < 0, number_list)) 
print(less_than_zero) 

The output of the above example is:


[-5, -4, -3, -2, -1] 

Example 2: in an list, delete the even Numbers and keep only the odd Numbers. You can write:


def is_odd(n): 
  return n % 2 == 1 
 
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])) 

The output result of the program is:


[1, 5, 9, 15] 

Note: the filter() function returns 1 Iterator, or 1 iterator, so to force filter() to complete the calculation, you need to use the list() function to get all the results and return list.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: