Create a list of lists of lists in a single line

Question:

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?

Asked By: Bas R

||

Answers:

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)
Answered By: I'mahdi

Using list comprehension:

vals = [[[] for _ in range(25)] for _ in range(25)]
Answered By: dm2

Just a fun hack for lazy people:

vals = eval(repr([[[]] * 25] * 25))
Answered By: Kelly Bundy

You can also use this approach based on map:

vals = list(map(lambda _: list(map(lambda __: [], range(25))), range(25)))
Answered By: Melchia

numpy way:

import numpy as np

vals = np.zeros((25,25,0)).tolist()
Answered By: jvx8ss

Fix size grouping from a flat list

n = 25
n_rows, n_cols = n, n

vals = [[[] for _ in range(n_rows*n_cols)][n_cols*i:(i+1)*n_cols] for i in range(n_rows)]
Answered By: cards
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.