Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a multi-dimensional list

Tags:

python

list

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?

like image 756
fdmillion Avatar asked Jul 14 '13 04:07

fdmillion


People also ask

How do you define a multidimensional list?

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.

How do you initialize a multi dimensional list in python?

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.

How do you create a multidimensional array?

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.

What is multidimensional list in C++?

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];


2 Answers

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

[[0 for i in range(10)] for j in range(10)]
like image 168
llb Avatar answered Sep 22 '22 05:09

llb


You can do it quite efficiently with a list comprehension:

a = [[0] * number_cols for i in range(number_rows)]
like image 45
cheeyos Avatar answered Sep 23 '22 05:09

cheeyos