3

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?

Bas R
  • 175
  • 7

5 Answers5

9

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)
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
4

Using list comprehension:

vals = [[[] for _ in range(25)] for _ in range(25)]
dm2
  • 4,053
  • 3
  • 17
  • 28
1

numpy way:

import numpy as np

vals = np.zeros((25,25,0)).tolist()
jvx8ss
  • 529
  • 2
  • 12
0

You can also use this approach based on map:

vals = list(map(lambda _: list(map(lambda __: [], range(25))), range(25)))
Melchia
  • 22,578
  • 22
  • 103
  • 117
-1

Just a fun hack for lazy people:

vals = eval(repr([[[]] * 25] * 25))
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65