Saturday, August 1, 2009

Python: Multidimensional array


Share at Facebook

In python, multiple dimensional array is slightly different. Its not like C/C++ or that kind of language. I'm giving you an example code regarding two dimensional array, and small explanation of it.

Here is a way to declare a 5x5 array at python.

array = [ [0 for col in range(5) ] for row in range(5)]


This will give you 5x5 2-d array. What does that code mean? Here,
Initialize Value = 0
for col in range(5) = create a linear or one dimensional array with 5 field and all are initialized with 0.

Now change the initializing value,
Initialize Value = [0 for col in range(5) ]
for row in range(5) = on each five rows of your array will contain a copy of above array.

So each row has pointing to another row. Which is nothing but a 2-d array.




5 comments:

Thejaswi.H.Raya said...

Or you could just do this:
array = [[0]*5] * 5

Anonymous said...

No, that won't work at all. In [[0]*5]*6, the outer *6 will create 6 references to the *same* array! This is not what you want at all.

K & H said...

Although you could save some some keystrokes with:
[[0]*5 for row in range(5)]

K & H said...

Although you could save some keystrokes with:
[[0]*5 for row in range(5)]

Emk said...

Thank you very much! This helped me greatly.