2

I was solving a problem on hackerrank and encountered a problem reading inputs.

The input format is:

First line: A number n, which tells the no. of lines I have to read.

n lines: Two space separated values, e.g.:

1 5

10 3

3 4

I want to read the space separated values in two lists. So list 'a' should be [1,10,3] and list 'b' should be [5,3,4].

Here is my code:

dist = []
ltr = []
n = input()
for i in range(n):
    ltr[i], dist[i] = map(int, raw_input().split(' '))

It gives me following error:

ltr[i], dist[i] = map(int, raw_input().split(' '))

IndexError: list assignment index out of range.

2
  • Note that you shouldn't use input in Python 2, since it's insecure and allows a user to execute arbitrary code on your machine. If you want integers, convert the strings that raw_input returns with the int function, e.g.: n = int(raw_input()). In Python 3 raw_input has been renamed to input and Python 2's input function doesn't exist anymore. Commented Jun 21, 2017 at 13:47
  • 1
    I appreciate your advice. Thanks for letting me know this fact. Commented Jun 21, 2017 at 18:31

2 Answers 2

5

This is a common error with Python beginners.

You are trying to assign the inputted values to particular cells in lists dist and ltr but there are no cells available since they are empty lists. The index i is out of range because there is yet no range at all for the index.

So instead of assigning into the lists, append onto them, with something like

dist = []
ltr = []
n = input()
for i in range(n):
    a, b = map(int, raw_input().split(' '))
    ltr.append(a)
    dist.append(b)

Note that I have also improved the formatting of your code by inserting spaces. It is good for you to follow good style at the beginning of your learning so you have less to overcome later.

Sign up to request clarification or add additional context in comments.

3 Comments

I think it would be clearer if you put those lines in the loop where they belong
@Lethr: I was trying to keep my answer concise and minimal, but I see your point. I have edited my answer accordingly. Thanks for the advice.
Nice explanation Rory.. Thank a lot.
0

This might help you in some way; here's a simpler way to approach this problem as you know "Simple is better than complex.":

dist=[]
ltr=[]
n=int(raw_input())
for i in range(n):
    dist.append(int(raw_input()))
    ltr.append(int(raw_input()))

print(dist)
print(ltr)

output:

[1, 10, 3]
[5, 3, 4]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.