# function filter name ==/ 'omar', 'omer', 'osama', 'ahmed', 'mahmuod', 'abdelrhman'
# and we need just name's start with 'o'
def name(n):
return n.startswith("o")
names_list = ['omar', 'omer', 'osama', 'ahmed', 'mahmuod', 'abdelrhman']
x = filter(name, names_list)
for l in x:
print(l)
print("#" * 100)
# function filter number ==/ 1, 20 , 38 , 550 , 3 and we need the numbers bigger than 2
def num(number):
if number > 2.5:
return number
num_list = [1, 20, 38, 550, 3]
my_num = filter(num, num_list)
print(list(filter(num, num_list))) # Without Loop.
for n in my_num: # With Loop.
print(n)
print("#" * 100)
# function filter name with lambda :-
n = ['omar', 'omer', 'osama', 'ahmed', 'mahmuod', 'abdelrhman']
for p in filter(lambda name: name.startswith("a"), n):
print(p)
print("#" * 100)
# function filter number with lambda :-
num_list = [1, 20, 38, 550, 3]
for N in filter(lambda num: num > 2.4, num_list):
print(N)
# filter is just filters things
my_list = [1, 2, 3, 4, 5, 6, 7]
def only_odd(item):
return item % 2 == 1 # checks if it is odd or even
print(list(filter(only_odd, my_list)))
"""filter() is a higher-order built-in function that takes a function and iterable as
inputs and returns an iterator with the elements from the iterable for which the function
returns True"""
"""The code below uses filter() to get the names in cities that are fewer than 10
characters long to create the list short_cities"""
cities = ["New York City", "Los Angeles", "Chicago", "Mountain View", "Denver", "Boston"]
def is_short(name):
return len(name) < 10
short_cities = list(filter(is_short, cities))
print(short_cities)
>>>['Chicago', 'Denver', 'Boston']