Search code examples
pythonpython-3.xindex-error

Basic Python - finding difference between elements in a list - IndexError


I'm trying to find the daily increase in a bank account for 5 days. I have a list created. I need to create a new list tracking those daily increases so that later on I can find an average increase, max increase, etc. The problem I'm having is I keep getting an Indexerror. Can anyone please help me? I'm getting very frustrated. I've done similar coding before (without determining difference between 2 elements) and I have no problem. The moment I add math to the module, it blows up.

Code is below (the reason I have all the print statements is a double-check to make sure the lists are correct):

acct_balance = [9852.24,9854.25,9954.24,9985.56,10056.98]

index = 0
total = 0
amt_increase = []
while index < len(acct_balance):
    if index != 0:
        change = acct_balance[index+1] - acct_balance[index]
        amt_increase.append(change)
        total = total + change
    index = index + 1

print('Account balances: ',acct_balance)
print('Daily Increase: ',amt_increase)
print('Total Increases: ',total)

I then get the below error when I try to run it:

Traceback (most recent call last):
  File "C:\Users\Rogue\Desktop\Rogue Help\HELP.py", line 9, in <module>
    change = acct_balance[index+1] - acct_balance[index]
IndexError: list index out of range

This is for school, so I can't use coding I've never seen before, and therefore don't understand. Thank you!


Solution

  • acct_balance = [9852.24,9854.25,9954.24,9985.56,10056.98]
    acct_increase = []
    
    for index, value in enumerate(acct_balance):
        if index == 0:
            continue
        acct_increase.append(acct_balance[index] - acct_balance[index - 1])
    

    They say there are two hard things in computer science: naming conventions, cache misses, and off-by-one errors.

    Instead of looking forward in the array (which is causing you to look over the end), always look backwards after skipping the 0th element. Also dont use while loops for looping over arrays in python, always use for-each loops. Do I get your homework credit :)