I can produce the list [0, 2, 6, 12, 20, 30, 42, 56, 72, 90]
using the following code:
x = []
y = 0
for i in range(2,21,2):
x.append(y)
y += i
However I'm not sure how to convert this into list comprehension syntax of the form
[expression for value in iterable if condition ]
You can assign to y
inside the comprehension, using an assignment expession, i.e. using :=
:
y = 0
x = [y := y + i for i in range(0,20,2)]
Alternatively, you can make use of the fact that these are doubles of triangular numbers, and then you don't need y
(but multiplication):
x = [i * (i + 1) for i in range(10)]