简体   繁体   中英

Python list: index out of range?

def purchase(amount, day, month, country):
    global history
    history += [0, 0, days_in_months(month - 1) + day]
    if history[len(history) - 1] <= history[len(history)]:
        return "Successful purchase"
    else:
        return "error"

When I try to run this I get the message "list index out of range" How do I fix this?

Because history[len(history)] is accessing beyond the limit of the array, if you have an array of 3 elements for example, the last element would be history[2] while len(history) would be 3 which is beyond the limit. Arrays count from 0 in Python.

You're trying to look up the nth index of a list with n entries. That will always fail. Eg a list of length 3 will never have a value stored at index 3 as the indices are zero based and therefore are 0, 1, 2.

In your case history[len(history) - 1] will return the last element of history , you can't go beyond that index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM