Skip to content

Instantly share code, notes, and snippets.

@AndyDeNike
Last active September 4, 2019 16:27
Show Gist options
  • Save AndyDeNike/a63cd4fb55e32bf8ba1bf02281440ce4 to your computer and use it in GitHub Desktop.
Save AndyDeNike/a63cd4fb55e32bf8ba1bf02281440ce4 to your computer and use it in GitHub Desktop.

Lambda meets filter

Essentially a lambda is just an anonomyous function; no 'def' declaration is necessary, only the 'lambda' keyword. Functionally a lambda is just a function! Consider using lamdba to define smaller, non complex functions.

lambda x: x

functionally the same as

def example(x): return x

Use a filter fucntion and pass a lambda as the first parameter of the filter. The second parameter of filter will be the list_range. Your goal is to return a filtered list of only the even numbers in the list_range passed.

Refresher: filter function will take a first parameter of a function (in the case of this excercise a lambda function) and a second parameter of a collection. This lambda function will be run upon each index of the colleciton and if it returns True this index will be included in the final filter output (if False, it will be omitted and filter will move onto the next index of the given collection). Keep in mind, filter only includes values that return as True!

# main.py
def filter_with_lambda(list_range):
pass
# tests.py
def test_filter_even_num_list_range():
assert list(filter_with_lambda(range(11))) == [0, 2, 4, 6, 8, 10]
def test_filter_even_num_list_range_2():
assert list(filter_with_lambda(range(10,21))) == [10, 12, 14, 16, 18, 20]
# solution.py
def filter_with_lambda(list_range):
return filter(lambda x: x%2 == 0, list_range)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment