I want to initialize a multidimensional list. Basically, I want a 10x10 grid - a list of 10 lists each containing 10 items.
Each list value should be initialized to the integer 0.
The obvious way to do this in a one-liner: myList = [[0]*10]*10
won't work because it produces a list of 10 references to one list, so changing an item in any row changes it in all rows.
The documentation I've seen talks about using [:]
to copy a list, but that still won't work when using the multiplier: myList = [0]*10; myList = myList[:]*10
has the same effect as myList = [[0]*10]*10
.
Short of creating a loop of myList.append()
s, is there a quick efficient way to initialize a list in this way?
They contain a list of elements separated by comma. But sometimes lists can also contain lists within them. These are called nested lists or multidimensional lists.
Each list value should be initialized to the integer 0. The obvious way to do this in a one-liner: myList = [[0]*10]*10 won't work because it produces a list of 10 references to one list, so changing an item in any row changes it in all rows.
You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.
C++ allows multidimensional arrays. Here is the general form of a multidimensional array declaration − type name[size1][size2]...[sizeN]; For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array − int threedim[5][10][4];
This is a job for...the nested list comprehension!
[[0 for i in range(10)] for j in range(10)]
You can do it quite efficiently with a list comprehension:
a = [[0] * number_cols for i in range(number_rows)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With