Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 number of elements in the array (both rows and columns).

like image 843
SyncMaster Avatar asked Nov 18 '11 13:11

SyncMaster


People also ask

How do you make an array two-dimensional in python?

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,...],. . . .]


1 Answers

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']) 
like image 131
ThiefMaster Avatar answered Oct 08 '22 08:10

ThiefMaster