Search code examples
pythonlistindex-error

Python IndexError: list index out of range (2D list)


I am new to python and currently testing out 2d lists.

This program uses a 2d list to store the sales of 3 types of noodle for each day in a week.

Also, in every day, there will also be a column that stores the total sales per day.

However, I am getting an IndexError where I can't seem to figure out what went wrong.

Sales = [[]]

def enterSales(arr):

    i = 0
    j = 0
    total_per_day = 0

    while i < 7:

        day = {
            0: "Monday",
            1: "Tuesday",
            2: "Wednesday",
            3: "Thursday",
            4: "Friday",
            5: "Saturday",
            6: "Sunday"
        }

        print("Enter " + day[i] + " sales for...")

        for j in range(3):

            noodle = {
                0: "Dried",
                1: "Dark",
                2: "Spicy",
            }

            arr[i].append(int(input(noodle[j] + " noodle: ")))

            # calculate total sales per day
            total_per_day += arr[i][j]

        arr[i].append(total_per_day)
        i += 1


def totalWeeklySales(arr):

    total_sales_per_week = 0

    for i in range(7):

        total_sales_per_week += arr[i][3]

    return total_sales_per_week


enterSales(Sales)
value = totalWeeklySales(Sales)
print("Total sales of the week is", value, ".")

enter image description here


Solution

  • In your for loop you have to add empty list for each i loop.

    add below line before incrementing i

    arr[i].append(total_per_day) # after this line in your code
    arr.append([])  #add this line