SyncMaster SyncMaster - 6 months ago 45
Python Question

Two dimensional array in python

I want to know how to declare a two dimensional array in Python.

arr = [[]]

arr[0].append("aa1")
arr[0].append("aa2")
arr[1].append("bb1")
arr[1].append("bb2")
arr[1].append("bb3")


The first two assignments work fine. But when I try to do, arr[1].append("bb1"), I get the following error,

IndexError: list index out of range.

Am I doing anything silly in trying to declare the 2-D array

[edit]:
but i do not know the no. of elements in the array (both rows and columns).

Answer

You do not "declare" arrays or anything else in python. You simply assign to a (new) variable. If you want a multidimensional array, simply add a new array as an array element.

arr = []
arr.append([])
arr[0].append('aa1')
arr[0].append('aa2')

or

arr = []
arr.append(['aa1', 'aa2'])
Comments