pythonlistflask

List does not append correctly (index out of range)


Why this does not work?

current_stock_dict = db.execute("SELECT * FROM current_stocks WHERE c_user_id=:user_id ", user_id=session["user_id"])

    # make a list for the mainpage
    mainpage_list = [[],[]]

    # save the lengh of the dict
    lengh_dict = len(current_stock_dict)
    price_sum = 0
    share_sum = 0

    # iterate over all rows in the dict
    for i in range(0, (lengh_dict - 1)):

        # lookup the symbol in the current stocks
        c_symbol = current_stock_dict[i]["c_symbol"]
        lookup_symbol = lookup(c_symbol)

        # append the symbol to the list for the mainpage
        mainpage_list[i].append(c_symbol)

        # append the name of the share
        share_name = lookup_symbol["name"]
        mainpage_list[i].append(share_name)

        # append the count of shares for mainpage
        c_count = current_stock_dict[i]["c_count"]
        mainpage_list[i].append(c_count)

        # append the current price
        share_price = lookup_symbol["price"]
        mainpage_list[i].append("$" + str(share_price))

        # append the total price of all shares
        total_price = float(share_price) * int(c_count)
        mainpage_list[i].append("$" + str(total_price))

        # count up the price and shares
        price_sum += total_price
        share_sum += c_count

When I run my website via Flask I get:

**IndexError: list index out of range**
in the line:
 ``` mainpage_list[i].append(c_symbol) ```
(and i guess if it did not allready fail there i'd get it for the rest of the lines too).

As long as lengh_dict = len(current_stock_dict) is 3 or less (so the database table has 3 rows or less) the code works.


Solution

  • Let's look at the relevant part of your code.

    mainpage_list = [[],[]]
    for i in range(0, (lengh_dict - 1)):
        mainpage_list[i].append(c_symbol)
    

    mainpage_list is a list that contains two elements, both of which are empty lists. So, accessing mainpage_list[0] is the first list inside mainpage_list, and mainpage_list[1] is the second empty list. Any index above that will result in an IndexError.

    It is not exactly clear what you are trying to achieve, but you could initialize mainpage_list with the correct number of empty lists inside if that is what you need, e.g. for the case where you want as many empty lists as the length of current_stock_dict, you could do

    mainpage_list = [ [] for _ in range(length_dict) ]