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?
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)
You can also use this approach based on map
:
vals = list(map(lambda _: list(map(lambda __: [], range(25))), range(25)))