web-profile

Python filter

Python filter

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]

def even(n):
    return n % 2 == 0

evens = list(filter(even, nums))
print(evens) # [2, 4, 6, 8]

# lambda
evens_lambda = list(filter(lambda x: x%2==0, nums))
print(evens_lambda) # [2, 4, 6, 8]

Leave a Reply

Your email address will not be published.