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

Create a list of lists of lists in a single line

This code creates a list of 25 lists of 25 lists:

vals = []
for i in range(25):
    vals.append([])
    for j in range(25):
        vals[i].append([])

How could I translate this code to a single line instead of using 5 lines in Python?

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 use list_comprehension.

res = [[[] for _ in range(25)] for _ in range(25)]

To check that result is the same, we can use numpy.ndarray.shape.

>>> import numpy as np
>>> np.asarray(vals).shape
(25, 25, 0)

>>> np.asarray(res).shape
(25, 25, 0)
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