Codied To Clipboard !
Home > Notes > python
The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not
ages = [5, 12, 17, 28, 24, 32] def myFunc(x): if x > 18: return False else: return True adults = filter(myFunc, ages) #print(adults) print(list(adults)) #for x in adults: # print(x)
The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not
# a list contains both even and odd numbers. seq = [0, 1, 2, 3, 5, 8, 13] # result contains odd numbers of the list #result = filter(lambda x: x % 2, seq) #print(list(result)) # result contains even numbers of the list result = filter(lambda x: x % 2 == 0, seq) print(list(result))
The filter function in Python is a built-in function used to construct an iterator from elements of an iterable (like lists, tuples, or strings) for which a function returns true. It is commonly used for filtering elements based on some criteria.
ages = [5, 12, 17, 28, 24, 32] def myFunc(x): if x > 18: return False else: return True adults = filter(myFunc, ages) #print(adults) print(list(adults)) #for x in adults: # print(x)
The filter function in Python is a built-in function used to construct an iterator from elements of an iterable (like lists, tuples, or strings) for which a function returns true. It is commonly used for filtering elements based on some criteria.
# a list contains both even and odd numbers. seq = [0, 1, 2, 3, 5, 8, 13] # result contains odd numbers of the list #result = filter(lambda x: x % 2, seq) #print(list(result)) # result contains even numbers of the list result = filter(lambda x: x % 2 == 0, seq) print(list(result))