I want to know how to declare a two dimensional array in Python.
arr = [] arr.append("aa1") arr.append("aa2") arr.append("bb1") arr.append("bb2") arr.append("bb3")
The first two assignments work fine. But when I try to do,
arr.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?
but I do not know the number of elements in the array (both rows and columns).
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.append('aa1') arr.append('aa2')
arr =  arr.append(['aa1', 'aa2'])
There aren't multidimensional arrays as such in Python, what you have is a list containing other lists.
>>> arr = [] >>> len(arr) 1
What you have done is declare a list containing a single list. So
arr contains a list but
arr is not defined.
You can define a list containing two lists as follows:
arr = [,]
Or to define a longer list you could use:
>>> arr = [ for _ in range(5)] >>> arr [, , , , ]
What you shouldn't do is this:
arr = [] * 3
As this puts the same list in all three places in the container list:
>>> arr.append('test') >>> arr [['test'], ['test'], ['test']]