0
0
Pythonprogramming~5 mins

Basic list comprehension syntax in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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:
[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]]
A[2, 3, 4]
B[1, 2, 3]
C[0, 1, 2]
D[1, 3, 5]
Which part of a list comprehension is the 'iterable'?
AThe expression before 'for'
BThe variable after 'for'
CThe brackets []
DThe sequence after 'in'
What does this list comprehension do?
[x for x in range(5)]
ACreates a list of 5 zeros
BCreates a list of numbers 1 to 5
CCreates a list of numbers 0 to 4
DCreates an empty list
Which of these is a valid list comprehension?
Afor x in [1, 2, 3]: x * 2
B[x * 2 for x in [1, 2, 3]]
C[x * 2 in [1, 2, 3]]
Dx * 2 for x in [1, 2, 3]
What type of value does a list comprehension produce?
AA list
BA string
CAn integer
DA dictionary
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.