1ages = [5, 12, 17, 18, 24, 32]
2def myFunc(x):
3 if x < 18:
4 return False
5 else:
6 return True
7
8adults = filter(myFunc, ages)
9for x in adults:
10 print(x) # 18 24 32
1nums1 = [2,3,5,6,76,4,3,2]
2
3def bada(num):
4 return num>4 # bada(2) o/p: False, so wont return.. else anything above > value returns true hence filter function shows result
5
6filters = list(filter(bada, nums1))
7print(filters)
8
9(or)
10
11bads = list(filter(lambda x: x>4, nums1))
12print(bads)
13
1# filter is just filters things
2
3my_list = [1, 2, 3, 4, 5, 6, 7]
4
5
6def only_odd(item):
7 return item % 2 == 1 # checks if it is odd or even
8
9
10print(list(filter(only_odd, my_list)))
11
1>>> numbers = [-2, -1, 0, 1, 2]
2
3>>> # Using a lambda function
4>>> positive_numbers = filter(lambda n: n > 0, numbers)
5>>> positive_numbers
6<filter object at 0x7f3632683610>
7>>> list(positive_numbers)
8[1, 2]
9
10>>> # Using a user-defined function
11>>> def is_positive(n):
12... return n > 0
13...
14>>> list(filter(is_positive, numbers))
15[1, 2]
1number_list = range(-5, 5)
2less_than_zero = list(filter(lambda x: x < 0, number_list))
3print(less_than_zero)
4
5# Output: [-5, -4, -3, -2, -1]
6
1 method number orbital_period mass distance year
20 Radial Velocity 1 269.30 7.10 77.40 2006
32 Radial Velocity 1 763.00 2.60 19.84 2011
43 Radial Velocity 1 326.03 19.40 110.62 2007
56 Radial Velocity 1 1773.40 4.64 18.15 2002
67 Radial Velocity 1 798.50 NaN 21.41 1996
7