Search code examples
pythonarrayspython-2.7inputraw-input

Python2 - IndexError: creating an array of arrays


Well this is a piece of my script:

k = int(raw_input())
order = []
o = []
for i in range(1, k):
    o.append(raw_input())
    order.append([int(n) for n in list(o[i])])

and I've been getting the following error after these input lines:

3
241356789



 Traceback (most recent call last):
  File "[path]", line 11, in <module>
    order.append([int(n) for n in list(o[i])])
IndexError: list index out of range

But I just cannot figure out why. Can anybody help me please? (I'm a beginner)


Solution

  • so, range(1, k) (in Python 2) gives you a list [1, 2, 3, ..., k-1]. When you append the list o by something from the input, the element is available on index 0

    >> o = []
    >> o.append(42)
    >> o[0]
    42
    

    But, in your loop you try to get index 1, which is not available.

    Remember, that the first element in a list is available through index 0, where the second has index 1 etc..