Multi-dimentional List in Python

Multi-dimentional list syntax in python is not as simple as I thought like

1
MyList = 3 * [ 3 * [ 3 * [0]]]

and then, try to modify a value in it, MyList[0][0][0] = 1, you will see there will be 9 items with value 1, this is not we expecte a normal multi-dimentional list should do.

the problem is python instead of create a new instance of list, it copy the Reference of it. I misused it, and bugged me for a while, after digging on the net, came up with 3 different ways.

comprehension

1
2
3
4
MyList = [[[0 for _ in range(3)] for _ in range(3)] for _ in range(3)]

#operate
MyList[0][0][0] = 1

simulate with dict

with collection.defaultdict help

1
2
3
4
5
6
7
from collections improt defaultdict

MyList = defaultdict(int)

#operate
MyList[0,0,0] = 1
MyList[0,1,2] = 'Good'

this give us a very similar syntax provided by NumPy

use NumPy array

1
2
3
4
5
import numpy as np
MyList = np.zeros((3,3,3))

#operate
MyList[0,0,0] = 1

this way unlike the other two above, only numbers is allowed.

Comments