Search code examples
pythonindex-error

I am getting an Index Error in the following code and i am very confused as to why


In the following code its showing me to have an index error. I am very confused as to where the mistake is.

the_list = [[0] * i for i in range(10)]
for i in range(10):
    for j in range(10):
        the_list[i][j] = i * j
for i in range(10):
    for j in range(10):
        print(the_list[i][j], end=", ")
    print()

Solution

  • You're creating a triangular list-of-lists, but the indexing patterns that follow suggest you want a square list-of-lists. If that's the case, change:

    the_list = [[0] * i for i in range(10)]
    

    to:

    the_list = [[0] * 10 for i in range(10)]
    

    On the other hand, if you really intended to create a triangular list-of-lists, then instead of changing the list creation, you would need to change the indexing patterns that follow from:

    for i in range(10):
        for j in range(10):
    

    to:

    for i in range(10):
        for j in range(i):