0
0
Pythonprogramming~5 mins

Lambda with filter() in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a lambda function in Python?
A lambda function is a small anonymous function defined with the keyword lambda. It can take any number of arguments but has only one expression, which is returned.
Click to reveal answer
beginner
What does the filter() function do in Python?
filter() takes a function and a list (or any iterable) and returns a new iterator with only the items for which the function returns True.
Click to reveal answer
beginner
How do you combine lambda and filter() to get even numbers from a list?
Use filter() with a lambda that checks if a number is even:
filter(lambda x: x % 2 == 0, numbers)
Click to reveal answer
intermediate
What type of object does filter() return in Python 3?
filter() returns an iterator, which can be converted to a list using list().
Click to reveal answer
intermediate
Why use lambda with filter() instead of a named function?
Using lambda keeps the code short and readable when the filtering logic is simple and used only once.
Click to reveal answer
What does this code return?
list(filter(lambda x: x > 3, [1, 4, 2, 5]))
A[1, 2]
B[4, 5]
C[1, 4, 2, 5]
D[3, 4, 5]
Which of these is a correct use of filter() with a lambda to get odd numbers?
Afilter(lambda x: x % 2 == 1, numbers)
Bfilter(lambda x: x % 2 == 0, numbers)
Cfilter(lambda x: x > 2, numbers)
Dfilter(lambda x: x < 0, numbers)
What type of argument does filter() expect as its first parameter?
AA number
BA list
CA string
DA function that returns True or False
What will list(filter(lambda x: x, [0, 1, '', 'hello'])) return?
A[1, 'hello']
B[0, 1]
C[0, '', 'hello']
D[]
Why might you convert the result of filter() to a list?
ABecause <code>filter()</code> returns a dictionary
BBecause <code>filter()</code> returns a string
CBecause <code>filter()</code> returns an iterator, and lists are easier to use and print
DBecause <code>filter()</code> returns a number
Explain how to use a lambda function with filter() to select items from a list.
Think about how lambda defines a small function and filter uses it to keep certain items.
You got /3 concepts.
    Describe the difference between the output of filter() in Python 2 and Python 3.
    Consider what you get directly from filter() and how you can use it.
    You got /3 concepts.