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

Best way to create list [ [1,2,3], [4,5,6] ] in Python

I want to generate the list of list [[1,2,3],[4,5,6]]

I have attached some python codes but I do not know what to pick among them in terms of efficiency:

[[y + x for x in range(3)] for y in [1,4]]
[[y for y in range(z, z + 3)] for z in [1,4]]
[[y, y + 1, y + 2] for y in [1,4]]

They all generate the required list however I do not feel satisfied with how they are written (since they are all dependent on getting values from the list [1,4]) and considering that I am only a beginner in the Python language. Can you also recommend me a good way to generate the list required? Thank you

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 :

[[y + x for x in range(3)] for y in [1,4]]

In this code, Giving the value 4 is not the best way because in order to print a list like this

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 21], [22, 23, 24], [25, 26, 27], [28, 29, 30]]

you might have to write

[[y + x for x in range(3)] for y in [1,4,7,10,13,16,19,22,25,28]]

which is not an easy and generalised code.Instead you can write

[[ x for x in range(y,y+3)] for y in range(1,6,3)]

or

[[ x for x in range(y,y+3)] for y in range(1,n,3)]
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