You can do it quite efficiently with a list comprehension:
a = [[0] * number_cols for i in range(number_rows)]
Answer from cheeyos on Stack OverflowPython 2.7 creating a multidimensional list - Stack Overflow
Multidimensional Lists - creating, reading and updating
Python Multidimensional List / Array - Stack Overflow
Multidimensional lists creation, why the weird behavior
https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly
More on reddit.comYou 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)]
I think your list comprehension versions were very close to working. You don't need to do any list multiplication (which doesn't work with empty lists anyway). Here's a working version:
>>> y = [[[] for i in range(n)] for i in range(n)]
>>> print y
[[[], [], [], []], [[], [], [], []], [[], [], [], []], [[], [], [], []]]
looks like the most easiest way is as follows:
def create_empty_array_of_shape(shape):
if shape: return [create_empty_array_of_shape(shape[1:]) for i in xrange(shape[0])]
it's work for me
New to python but not other higher level languages.
I’m having difficulty understanding how to use multidimensional lists in python.
I have a list if 256 objects. Each object has 6 variables. In other languages, I could read and update/change similar to
object[0] = [1,2,3,4,5,6]
…
object[255] = [1,2,3,4,5,6] Etc.
I understand in python this isn’t possible, so I’ll have to revert to something similar to
object = [[0], [1,2,3,4,5,6]]
…
object = [[255], [1,2,3,4,5,6]]
And reading will be similar to
var1 = object[0][3]
print(var1)
But I can’t get my head around it or find easy to,understand examples.
Does anyone have any quick and easy to digest resources that could help me understand this a bit better?
Thanks!