Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Produce this list [0, 2, 6, 12, 20, 30, 42, 56, 72, 90] using list comprehension syntax

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 ]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading