質問

I want to:

  1. Take two inputs as integers separated by a space (but in string form).
  2. Club them using A + B.
  3. Convert this A + B to integer using int().
  4. Store this integer value in 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?

役に立ちましたか?

解決

Why your error is occurring:

You can only reference an index of a list 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 the index 0, which does not exist as the list 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.

他のヒント

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

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)]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top