Reputation: 355
I want to:
input
s as integers separated by a space (but in string form).A + B
.A + B
to integer using int()
.list
C
.My code:
C = list()
for a in range(0, 4):
A, B = input().split()
C[a] = int(A + B)
but it shows:
IndexError: list assignment index out of range
I am unable understand this problem. How is a
is going out of the range
(it must be starting from 0
ending at 3
)?
Why it is showing this error?
Upvotes: 0
Views: 956
Reputation: 20351
Why your error is occurring:
You can only reference an
index
of alist
if it already exists. On the last line of every iteration you are referring to an index that is yet to be created, so for example on the first iteration you are trying to change theindex
0
, which does not exist as thelist
is empty at that time. The same occurs for every iteration.
The correct way to add an item to a list is this:
C.append(int(A + B))
Or you could solve a hella lot of lines with an ultra-pythonic list comprehension. This is built on the fact you added to the list
in a loop, but this simplifies it as you do not need to assign things explicitly:
C = [sum(int(item) for item in input("Enter two space-separated numbers: ").split()) for i in range(4)]
The above would go in place of all of the code that you posted in your question.
Upvotes: 1
Reputation: 113915
Here's a far more pythonic way of writing your code:
c = []
for _ in range(4): # defaults to starting at 0
c.append(sum(int(i) for i in input("Enter two space-separated numbers").split()))
Or a nice little one-liner:
c = [sum(int(i) for i in input("Enter two space-separated numbers").split()) for _ in range(4)]
Upvotes: 0
Reputation: 996
The correct way would be to append the element to your list like this:
C.append(int(A+B))
And don't worry about the indices
Upvotes: 0