Taylor Patterson Taylor Patterson - 1 year ago 67
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
was actually a list and both items are being added into the dictionary properly as well. The problem is with the
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:
print (groceryfood_list)

Answer Source

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

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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download