Search code examples
stringlistintegersublist

How to put string and integer in list by user input


Can you suggest me how to put integer and string in sub-list of list? For example:

Sample input:

Harry
37.21
Berry
37.21
Charli
37.2
Ron
41
Jack
39

Sample output:

[['Harry', 37.21], ['Berry', 37.21], ['Charli', 37.2], ['Ron', 41], ['Jack', 39]]

I have tried this:

students = []
for i in range(int(input("Enter num of students: "))):
    name = input("name of student: ")
    score = float(input("score:  "))
    students.append(name)
    students.append(score)
print(students)

But I am getting this:

['test1', 23.1, 'test2', 53.32]

Solution

  • Append a tuple (or list) instead of the single values:

    students = []
    for i in range(int(input("Enter num of students: "))):
        name = input("name of student: ")
        score = float(input("score:  "))
        students.append((name, score))
        # students.append([name, score]) # alternatively
    print(students)
    

    I suggest to use tuples instead of lists. Tuples are something similar like lists but cannot be modified after creation. I guess that this makes more sens in your example since your (student, score) is a data structure. Also tuples are faster because they are immutable.