Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 956
Prakash Shelar Avatar asked Oct 24 '25 21:10

Prakash Shelar


2 Answers

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)
like image 67
Barmar Avatar answered Oct 26 '25 10:10

Barmar


Use a dictionary instead of a list (a list will work, but for what you are doing a hashmap is better suited):

if __name__ == '__main__':
    scores = dict()
    for _ in range(int(input())):
        name = input()
        score = float(input())
        scores[name] = score
    print(scores)
like image 30
Victor Avatar answered Oct 26 '25 10:10

Victor