2

I am declaring multidimensional array in python

Nbrs[23][2] = [[1, 1], [1, 2], [2, 1], 
               [2, 3], [3, 2], [1, 3], 
               [3, 1], [1, 4], [3, 4], 
               [4, 3], [4, 1], [1, 5], 
               [2, 5], [3, 5], [4, 5], 
               [5, 4], [5, 3], [5, 2], 
               [5, 1], [1, 6], [5, 6], 
               [6, 5], [6, 1]
           ]

It gives me error as:

NameError: name 'Nbrs' is not defined

I cannot declare 2 dimensional array in python by this way?

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
sam
  • 18,509
  • 24
  • 83
  • 116
  • Python does not have declarations. [See also one of my previous top answers](http://stackoverflow.com/questions/11007627/python-variable-declaration/11008311#11008311). – Karl Knechtel Jan 18 '14 at 07:54

3 Answers3

1

You don't need to specify the dimensions when defining lists in python. When you type Nbrs[23][2] python is trying to find what's at [23][2] in Nbrs but in this case Nbrs doesn't exist because you are trying to define it for the first time here.

Instead do this:

Nbrs = [[1, 1], [1, 2], [2, 1], ....
shuttle87
  • 15,466
  • 11
  • 77
  • 106
1

Assignment statement:

Nbrs[23][2] = [[1, 1], [1, 2], [2
#    ^  ^ you can't index   Nbrs before it created 

should be:

Nbrs = [[1, 1], [1, 2], [2
# now after this statement, Nbrs a list of list you can access 
# its elements useng `Nbrs[i][j]`  for i < len(Nbrs) and j < 2 

I think you confuses because of C, C++ declarations!

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
1

That's not the right syntax. You don't need to include anything about the variable's type on the left-hand side; in particular, drop the dimensions.

Nbrs = [[1, 1], [1, 2], [2, 1], [2, 3], [3, 2], [1, 3], [3, 1], [1, 4], [3, 4], [4, 3], [4, 1], [1, 5], [2, 5], [3, 5], [4, 5], [5, 4], [5, 3], [5, 2], [5, 1], [1, 6], [5, 6], [6, 5], [6, 1]]

What you've written tries to assign to an element of Nbrs, which doesn't exist yet.

user2357112
  • 260,549
  • 28
  • 431
  • 505