What is [x * 2 for x in range(4)]?
Options
- [2, 4, 6, 8]
- [0, 2, 4, 6] (Correct option)
- [0, 1, 2, 3]
- [0, 2, 4, 6, 8]
Answer
[0, 2, 4, 6]
Why
range(4) gives 0, 1, 2, 3: four numbers, starting at 0 and stopping BEFORE 4.
The list comprehension multiplies each one by 2: [0, 2, 4, 6].
It is a short way to write a loop that builds a list.
result = []
for x in range(4):
result.append(x * 2)Remember
range(n) = 0 to n-1.