IndexError: list assignment index out of range with lists and input (). split ()

2

I'm trying to make a program in which the user has to enter a character and then assign it the value, and I want the character and value to be on the same line separated by a space, so I'm using input () .split () to separate it into 2 different lists, works perfectly if I only assign the value to one character, but when I try to assign the value to two or more characters I get the following error:

Traceback (most recent call last):
  File "Test.py", line 5, in <module>
    car[x], val[x] = input().split()
IndexError: list assignment index out of range

The fragment of my code that is causing the problem is the following:

K = input()
car = [K]
val = [K]
for x in range(int(K)):
    car[x], val[x] = input().split()
    
asked by Spiwocoal 06.10.2018 в 03:22
source

1 answer

2

The problem is that you incorrectly initialize the lists, car = [K] creates a list in which the elements are the characters of the string K , that is:

>>> ["5"]
['5']

>>> ["12"]
['1', '2']

This means that if k is "5" , for example, your lists only have one element, so car[0] is valid, but car[1] is no longer valid.

You should do something like this instead:

k = int(input())
car = [None] * k
val = [None] * k
for x in range(k):
    car[x], val[x] = input().split()
3
a 4
b 6
c 13

>>> car
['a', 'b', 'c']
>>> val
['4', '6', '13']

[None] * k create a list of k elements all None :

>>> [None] * 5
[None, None, None, None, None]
  

Note: Be careful when initializing a list in this way when it comes to mutable elements since all elements are references   to the same object:

>>> l = [[]] * 5
>>> l[0].append(2) 
>>> l
[[2], [2], [2], [2], [2]]
     

instead use a for:

>>> l = [[] for _ in range(5)]

Apparently a dictionary is the most appropriate structure to store the information you want, as long as the characters are unique:

k = int(input())
chars_count = dict((input().split() for _ in range(k)))
3
a 4
b 6
c 13

>>> chars_count
{'a': '4', 'b': '6', 'c': '13'}

>>> chars_count["c"]
"13"
>>> chars_counts["a"]
"4"

Another way, doing an entire casting of the value previously:

k = int(input())
chars_count = {}

for _ in range(k):
    char, value = input().split()
    chars_count[char] = int(value)

# Lo mismo usando diccionarios por compresión
# chars_count = {c: int(v)  for c, v in (input().split() for _ in range(k))}
3
a 4
b 6
c 13

>>> chars_count
{'a': 4, 'b': 6, 'c': 13}
    
answered by 06.10.2018 / 03:34
source