Search code examples
pythonlistrangetraceback

why is 'list index out of range' showing?


n = int(input())
students = list()
for i in range(0,n):
    students[i][0]=input("Name: "); students[i][1]=float(input("Grade: "))

I wrote this code but 'list index out of range' is showing. I don't understand why it is happening.

    ---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-46-966bd0f334a2> in <module>
      1 n = int(input())
      2 for i in range(0,n):
----> 3     students[i][0]=input(); students[i][1]=float(input())

IndexError: list index out of range

Please Help.


Solution

  • The reason your code doesn't work is that you're trying to assign students[i] when students is an empty list. Similarly, you're trying to assign students[i][0] and students[i][1] when students[i] doesn't even exist!

    The solution is simple: Instead of assigning to the list (x[1] = 3), append to the list (x.append(3)).

    n = int(input())
    students = list()
    for i in range(0,n):
        students.append([]) # Must add empty list otherwise students[i] doesn't exist
        students[i].append(input("Name: ")); students[i].append(float(input("Grade: ")))
        
    print(students)
    # Prints [['a', 1.0], ['b', 2.0], ['c', 3.0]]
    # after inputting 3, a, 1, b, 2, c, 3