Taylor Patterson Taylor Patterson - 8 days ago 5
Python Question

Why is the index out of range? (Python)

I run the code below and raise an error that says

food_quant = item[1]
list index out of range. I checked to make sure
item
was actually a list and both items are being added into the dictionary properly as well. The problem is with the
"Add"
command. Also, this is just a snippet because the rest of program is not relevant, so yes I do have proper dictionaries and lists defined above this part.

item = input("Please enter an item with its quantity separated by a hyphen (Ex. Apples-3) or any of the commands described above." )
item = item.split('-')
food_item = item[0]
food_quant = item[1]
foodquant_dict[food_item] = food_quant
if item == "Add":
for key in foodquant_dict:
groceryfood_list.append(key)
print (groceryfood_list)

Answer

If any input not containing at least on hyphen is given to your program (e.g. "add", or any arbitrary input not containing hyphen really), your progrma still attempts to set food_quant = item[1], which doesn't exist if the input doesn't have at least one hyphen (i.e. if there's nothing to split in the list, your item will be list that contains just that one item).

An example to illustrate the point:

>>> case1 = "item-2".split("-")
>>> case1
['item', '2']
>>> case2 = "item".split("-")
>>> case2
['item']

Clearly, calling case2[1] for the latter case would cause IndexError, because there is just one element in the list. You need to validate whether your input contains dashes or not, or validate whether the split list contains more than one element. An example to validate list length:

item = input("enter your input\n")
item = item.split("-")
if len(item) > 1:
    a = item[1]