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

One step list operation in Python

I have a list A. I am generating a new list by adding 1 to every element of the previous list and at the end, getting a combined list B+C+D. Is there a one step way to do this?

A=[12,8,4,0]
B=[i+1 for i in A]
C=[i+1 for i in B]
D=[i+1 for i in C]
print(B+C+D)

The current and expected output is

[13, 9, 5, 1, 14, 10, 6, 2, 15, 11, 7, 3]

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 do it like this:

[i+j for i in range(1, 4) for j in A]

This produces:

[13, 9, 5, 1, 14, 10, 6, 2, 15, 11, 7, 3]

It can also be done with itertools.product, but in this case I don’t think it buys you much:

[i+j for i, j in itertools.product(range(1, 4), A)]
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