Filtering basically just helps filter out certain values from a list. You take a function that returns a boolean value - true or false and filters out the values that return false when you apply that function to an item and keeps those that return True.
In [1]:
x = range(10)
In [2]:
x
Out[2]:
In [3]:
def divis_by_2(num):
return num % 2 == 0
In [4]:
divis_by_2(2)
Out[4]:
In [5]:
divis_by_2(3)
Out[5]:
In [16]:
list(map(divis_by_2, x))
Out[16]:
In [17]:
list(filter(divis_by_2, x))
Out[17]:
In [8]:
test_list = [
"hello",
"x,y,z. i like this.",
"this is two xx",
"this, x, here x is, here it is againx"
]
In [9]:
def has_x(my_string):
return my_string.count("x") >= 2
In [10]:
has_x("hello")
Out[10]:
In [11]:
has_x("xxhello")
Out[11]:
In [18]:
list(filter(has_x, test_list))
Out[18]:
It acts just like map, it maps values from true to false and helps us only get those that meet the criteria
In [14]:
list(map(has_x, test_list))
Out[14]:
In [ ]: