easy +8 pts

Boolean Mask Filter

Apply a boolean mask to a list and return the matching elements as a list.

Write a function `filter_by_mask(arr, mask)` that takes a list `arr` and a boolean mask list `mask`, both of the same length, and returns a Python list of the elements from `arr` where the corresponding element in `mask` is `True`. - Both `arr` and `mask` are plain Python lists of the same length. - The mask contains only boolean values (`True` or `False`). - The returned value must be a plain Python list in the original order. - If no elements are selected, return an empty list. - Do not modify the input lists.

Constraints

- `1 <= len(arr) <= 10^5` - `len(mask) == len(arr)` - Elements of `arr` can be any Python values (integers, floats, strings, etc.). - Time complexity: O(n), where n is the length of the input.

Example

```python
arr = [1, 2, 3, 4]
mask = [True, False, True, False]
filter_by_mask(arr, mask)  # [1, 3]

arr2 = [[10, 20], [30, 40]]
mask2 = [False, True]
filter_by_mask(arr2, mask2)  # [[30, 40]]

arr3 = [5, 6, 7]
mask0 = [False, False, False]
filter_by_mask(arr3, mask0)  # []
```
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a list comprehension to iterate over pairs: `[x for x, m in zip(arr, mask) if m]`.
Alternatively, use a loop with an index and append when `mask[i]` is True.
The result should preserve the original order of elements.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.