Python: initialize multi-dimensional list

You can do it quite efficiently with a list comprehension:

a = [[0] * number_cols for i in range(number_rows)]

This is a job for...the nested list comprehension!

[[0 for i in range(10)] for j in range(10)]

Just thought I'd add an answer because the question asked for the general n-dimensional case and I don't think that was answered yet. You can do this recursively for any number of dimensions with the following example:

n_dims = [3, 4, 5]

empty_list = 0
for n in n_dims:
    empty_list = [empty_list] * n

>>>empty_list
>>>[[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
   [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
   [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
   [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
   [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]]

Tags:

Python

List