Search code examples
pythonpython-3.xtypeerrornested-lists

How to append variables in nested list in python


if __name__ == '__main__':
    for _ in range(int(input())):
        name = input()
        score = float(input())
        a=[]
        a.append([name][score])
    print(a)

This is error occurred when I insert values

Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/Nested Lists.py", line 6, in <module>
    a.append([name][score])
TypeError: list indices must be integers or slices, not float

Solution

  • The syntax to make a list containing name and score is [name, score]. [name][score] means to create a list containing just [name], and then use score as an index into that list; this doesn't work because score is a float, and list indexes have to be int.

    You also need to initialize the outer list only once. Putting a=[] inside the loop overwrites the items that you appended on previous iterations.

    a=[]
    for _ in range(int(input())):
        name = input()
        score = float(input())
        a.append([name, score])
    print(a)