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):
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
Traceback (most recent call last):
File "C:/Users/--/--/1B.py", line 10, in <module>
TypeError: list indices must be integers, not tuple
You have to do
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:
a gives you the first list in
a now accesses the first list in
a, and then accesses the second element in that list.
If you did
b = a and then called
b, you'd get exactly the same behaviour - because that is what's happening when you do
a. 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.