Python Pop Quiz - Modulo List Comprehension
Python list comprehensions are great. The list comprehension is a way to take a Python for loop and make it a one-liner piece of code.
List comprehensions can include conditional statements that act like filters. They can even contain other list comprehensions, making them difficult to read and comprehend.
If you don’t know how to make a list comprehension, you should check out the Python documentation before you try this quiz.
The Quiz
When you run this code, what will print out?
print([x for x in range(10) if x % 2])A) []
B) [1, 3, 5, 7, 9]
C) [0, 2, 4, 6, 8]
D) [2, 6, 10, 14, 18]
Hint
If you get stuck, look up the modulo operator.
The Answer
B) [1, 3, 5, 7, 9]
Explanation
Why is the list full of odd numbers? The reason is the modulo operator. The modulo operator “yields the remainder from the division of the first argument by the second,” per the documentation.
To get a better feel for what’s going on, take a gander at these examples:
When there is a remainder, it returns 1; otherwise, it returns 0. In Quiz 6, you learned that zero is a falsey value and non-zero (i.e. one in this case) values are truthy.
So when you use the if x % 2 In your list comprehension, you are saying to keep the values that return 1 (the odd ones) and ignore the values that return 0.
There you have it! You have effectively filtered out ALL the even numbers in the range 0-9, yielding [1, 3, 5, 7, 9].
Want More Quizzes?
Check out my book, The Python Quiz Book, for over 100 more quizzes!



