-1

I've created a matrix like this:

b = [[0 for y in range(1,4)] for x in range(1,3)]

I want to have the indexes b[1:2][1:3] available, but the above code doesn't seem to do that.

range(1,4) should return numbers from 1 to 3, and range(1,3) should return numbers 1 and 2.

When i try to assign a value to b[1][3], i get an IndexError. What is the explanation of this?

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
Jesper
  • 2,644
  • 4
  • 30
  • 65

1 Answers1

0

range(1,4) is a list of length 3, therefore so is [0 for y in range(1,4)]. The indices available for a list are always from 0 up to the length of the list minus 1. If you want alternative indices use a dictionary.

>>> range(1, 4)
[1, 2, 3]
>>> for x in range(1, 4):
...     print(x)
...     
1
2
3
>>> L = [0 for y in range(1, 4)]
>>> L
[0, 0, 0]
>>> L[0]
0
>>> L[1]
0
>>> L[2]
0
>>> L[3]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: list index out of range
Alex Hall
  • 34,833
  • 5
  • 57
  • 89