What does [n for n in range(20) if n % 2 if n % 3] keep?
Consecutive if clauses all have to pass, like nested if statements: 1, 5, 7, 11, 13, 17, 19.
List Comprehensions · Exercise 1 of 4
Fifteen multiple-choice questions on Python comprehensions: filters, if-else, several for clauses, nesting, dict and set comprehensions, generator expressions and scope. Pick an option to check your answer instantly.
What does [n for n in range(20) if n % 2 if n % 3] keep?
Consecutive if clauses all have to pass, like nested if statements: 1, 5, 7, 11, 13, 17, 19.
What does result = [print(x) for x in range(3)] leave in result?
print returns None. Use a for loop when you only want the side effect.
What does len(x for x in range(5)) do?
A generator does not know how many values it will produce. Use sum(1 for …) or build a list.
Which expression creates a 3 × 3 grid whose rows are independent lists?
The comprehension evaluates [0] * 3 afresh for every row; * on the outer list repeats references to one row.
What is the length of {w.lower() for w in ["Hi", "hi", "HI", "hey"]}?
After lower-casing there are only two distinct values, "hi" and "hey", and a set keeps each once.
Timed online tests with instant scores and explanations.