Recall & Review
beginner
What does the
filter() function do in Python?The
filter() function takes a function and a sequence (like a list) and returns a new sequence with only the items for which the function returns True.Click to reveal answer
beginner
How do you use
filter() with a lambda function to keep only even numbers from a list?You write:
This keeps only numbers divisible by 2 (even numbers).
filter(lambda x: x % 2 == 0, my_list)This keeps only numbers divisible by 2 (even numbers).
Click to reveal answer
intermediate
What type of object does
filter() return in Python 3?It returns a
filter object, which is an iterator. You can convert it to a list using list() to see the filtered items.Click to reveal answer
intermediate
What happens if the function passed to
filter() is None?If the function is
None, filter() removes all items that are false in a Boolean context (like False, 0, '', None).Click to reveal answer
beginner
Can
filter() be used with any iterable, or only lists?filter() works with any iterable, such as lists, tuples, sets, or even strings.Click to reveal answer
What does
filter() return in Python 3?✗ Incorrect
filter() returns a filter object, which is an iterator. You can convert it to a list if needed.What happens if you pass
None as the function to filter()?✗ Incorrect
Passing
None makes filter() remove all items that are false in a Boolean context.Which of these is a correct way to use
filter() to keep only positive numbers from a list nums?✗ Incorrect
The function
lambda x: x > 0 keeps only numbers greater than zero.How can you see the filtered results from
filter()?✗ Incorrect
The filter object is an iterator, so converting it to a list shows the filtered items.
Can
filter() be used on a string?✗ Incorrect
Strings are iterable, so
filter() can be used directly on them.Explain how the
filter() function works and give an example using a lambda function to filter even numbers.Think about how you pick only certain items from a list based on a test.
You got /5 concepts.
What happens when you pass
None as the function to filter()? Why might this be useful?Consider what values are treated as false in Python.
You got /4 concepts.