0
0
Pythonprogramming~10 mins

filter() function in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to filter out even numbers from the list.

Python
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter([1], numbers))
print(even_numbers)
Drag options to blanks, or click blank then click option'
Alambda x: x % 2 == 0
Blambda x: x * 2
Clambda x: x + 2
Dlambda x: x - 2
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using a function that changes the number instead of returning True/False.
Forgetting to convert the filter object to a list.
2fill in blank
medium

Complete the code to filter words longer than 3 characters.

Python
words = ['cat', 'lion', 'dog', 'elephant']
long_words = list(filter([1], words))
print(long_words)
Drag options to blanks, or click blank then click option'
Alambda w: w.startswith('e')
Blambda w: len(w) > 3
Clambda w: w == 'dog'
Dlambda w: len(w) < 3
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using < 3 instead of > 3.
Filtering by exact word instead of length.
3fill in blank
hard

Fix the error in the filter function to keep only positive numbers.

Python
numbers = [-2, 0, 3, 5, -1]
positive = list(filter([1], numbers))
print(positive)
Drag options to blanks, or click blank then click option'
Alambda x: x != 0
Blambda x: x >= 0
Clambda x: x < 0
Dlambda x: x > 0
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Including zero as positive by using >= instead of >.
Filtering negative numbers instead of positive.
4fill in blank
hard

Fill both blanks to filter words starting with 'a' and convert them to uppercase.

Python
words = ['apple', 'banana', 'avocado', 'cherry']
filtered = list(filter([1], words))
result = [w.[2]() for w in filtered]
print(result)
Drag options to blanks, or click blank then click option'
Alambda w: w.startswith('a')
Blambda w: w.endswith('a')
Cupper
Dlower
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using endswith instead of startswith.
Using lower() instead of upper().
5fill in blank
hard

Fill all three blanks to filter numbers divisible by 3, square them, and keep only those greater than 10.

Python
numbers = [1, 3, 4, 6, 9, 12]
filtered = filter([1], numbers)
squared = map(lambda x: x[2]2, filtered)
result = list(filter(lambda x: x [3] 10, squared))
print(result)
Drag options to blanks, or click blank then click option'
Alambda x: x % 3 == 0
B**
C>
Dlambda x: x % 2 == 0
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using wrong lambda for filtering divisible numbers.
Using multiplication instead of exponentiation for squaring.
Using < instead of > in the last filter.