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 number of elements in the array (both rows and columns).
Syntax of Python 2D Array There is another syntax for creating a 2D array where initialisation (creation of array and addition of elements) is done with a single line of code. This syntax is as follows: array_name=[[r1c1,r1c2,r1c3,..],[r2c1,r2c2,r2c3,...],. . . .]
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With