Krishna Kumar Krishna Kumar - 2 years ago 85
Python Question

Error while Accessing 2d array in Python 2.7

I'm beginner in python and i want to access each elemnt in a 2d matrix.
i'm using this code.

for i in xrange(3):
for j in xrange(3):
print a
print a[0,2]

but while i'm executing the element at a[0,2] it's giving me an error.

[[0, 1, 2], [1, 2, 3], [2, 3, 4]]

Traceback (most recent call last):
File "C:/Users/--/--/", line 10, in <module>
print a[0,2]
TypeError: list indices must be integers, not tuple

can anyone help me out ? Any help would be aprreciated.

Answer Source

You have to do a[0][2], not a[0,2].

Cause of the Error

The error you are getting is because Python doesn't recognise 0,2 as a valid index. This is not surprising - indices are supposed to be pure integers only, not <integer>, <integer>. The Python interpreter recognises these as two separate integers, but doesn't know what to do with them.

Instead, what you really want is to think about it this way:

  • Doing a[0] gives you the first list in a.

  • Doing a[0][2] now accesses the first list in a, and then accesses the second element in that list.

If you did b = a[0] and then called b[2], you'd get exactly the same behaviour - because that is what's happening when you do a[0][2]. This is also the way how two-dimensional arrays are usually accessed in other languages as well, so it's good to know upfront how to work with them in this regard.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download