Skip to content
Advertisement

IndexError: list index out of range error on python

This is my code:

while True:
print("Type 'done' to finish receipts")
code=input("Enter item code to add:")
items =open("items.txt")
quant=input("Quantity:")
details = items.read()
detailslist = details.split("n")
for a in detailslist:
    fire = a.split("#")
    print (fire)
    b = fire[0]
    c = fire[1]
    d = fire[2]
    dictd = {}
    dictd[b] = c + ' ' +' Quantity: '+ ' ' + quant +' '+ 'Price:' + d
    print (dictd)       

This is in items.txt:

A# Almanac2018# 18.30
B# Almanac2020# 23.80
C# Almanac2021# 16.54
D# Almanac2022# 22.25

I am getting this error:

Type 'done' to finish receipts
Enter item code to add:A
Quantity:45
['A', ' Almanac2018', ' 18.30']
{'A': ' Almanac2018  Quantity:  45 Price: 18.30'}
['B', ' Almanac2020', ' 23.80']
{'B': ' Almanac2020  Quantity:  45 Price: 23.80'}
['C', ' Almanac2021', ' 16.54']
{'C': ' Almanac2021  Quantity:  45 Price: 16.54'}
['D', ' Almanac2022', ' 22.25']
{'D': ' Almanac2022  Quantity:  45 Price: 22.25'}
['']
Traceback (most recent call last):
  File "receipt.py", line 12, in <module>
    c = fire[1]
IndexError: list index out of range

I am trying to make a program that makes a receipt of items so if you could provide any code that would be helpful. Any help would be appreciated.

Advertisement

Answer

The problem you have in your code is with the empty strings in your items.txt file. When there’s an empty string, fire would resolve to [''], which is a list of only 1 item, so you get an error when the code tries to run c = fire[1]. You can add a check to see if it’s an empty line or not:

for a in detailslist:
    fire = a.split("#")
    if len(fire) > 1:
        print (fire)
        b = fire[0]
        c = fire[1]
        d = fire[2]
        dictd = {}
        dictd[b] = c + ' ' +' Quantity: '+ ' ' + quant +' '+ 'Price:' + d
        print (dictd)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement