We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Filter

The built-in filter function takes a function and an iterable (often a list) and returns an iterator that keeps elements from the original iterable only where the result of the function on that item returned True.

In Python:

def is_even(x: int) -> bool:
    return x % 2 == 0


numbers: list[int] = [1, 2, 3, 4, 5, 6]
evens: list[int] = list(filter(is_even, numbers))
print(evens)
# [2, 4, 6]

Assignment

Complete the remove_invalid_lines function. It accepts a document string as input. It should:

For example, this:

* Star Wars episode 1 is underrated
- Star Wars episode 9 is fine
* Star Wars episode 3 is the best

Should become:

* Star Wars episode 1 is underrated
* Star Wars episode 3 is the best

Tips

The following methods may be useful:

.join

"\n".join(["a", "b", "c"])
# a
# b
# c

.startswith

s: str = "hello"
s.startswith("h")
# True
s.startswith("o")
# False

.split

s: str = """hello
world"""
lines: list[str] = s.split("\n")
# ['hello', 'world']

If the string starts or ends with "\n", .split("\n") includes empty strings at the edges. Joining the pieces with "\n" preserves those newlines.