Recall & Review
beginner
What is list comprehension in Python?
List comprehension is a concise way to create lists by writing a single expression inside square brackets, often replacing loops and append calls.
Click to reveal answer
beginner
Write the basic syntax of a list comprehension.
The basic syntax is:
where
[expression for item in iterable]where
expression is the value to add, item is each element from iterable.Click to reveal answer
beginner
How does list comprehension compare to a for-loop for creating a list?
List comprehension is shorter and often easier to read. It combines the loop and list creation in one line, unlike a for-loop which needs multiple lines and an append call.
Click to reveal answer
beginner
Example: What does this list comprehension do?
[x * 2 for x in range(3)]It creates a list by multiplying each number from 0 to 2 by 2. The result is
[0, 2, 4].Click to reveal answer
beginner
Can list comprehensions include conditions?
Yes, but that is a more advanced topic. The basic syntax does not include conditions. Conditions are added with an
if clause inside the comprehension.Click to reveal answer
What is the output of this code?
[x + 1 for x in [1, 2, 3]]✗ Incorrect
Each element is increased by 1, so 1+1=2, 2+1=3, 3+1=4.
Which part of a list comprehension is the 'iterable'?
✗ Incorrect
The iterable is the sequence or collection after the 'in' keyword.
What does this list comprehension do?
[x for x in range(5)]✗ Incorrect
range(5) generates numbers 0 to 4, and the comprehension collects them as is.
Which of these is a valid list comprehension?
✗ Incorrect
Only option B follows the correct list comprehension syntax.
What type of value does a list comprehension produce?
✗ Incorrect
List comprehensions always produce a list.
Explain the basic syntax of a list comprehension and how it works.
Think about how you write a for-loop and how list comprehension shortens it.
You got /6 concepts.
Give an example of a simple list comprehension that doubles numbers from 0 to 4.
Use range and multiply each item by 2 inside the comprehension.
You got /5 concepts.