Home > OS >  Index i out of range for an array while using nested loops
Index i out of range for an array while using nested loops

Time:11-21

Starting to learn to code and I was doing the fantasy items exercise from automate boring stuff with python. I tried comparing each item of the addedItems array to the dictionary keys to see if they exist, if not I would create a new key with the default value 1. However it says that I have index out of range error, although creating a regular for loop and testing the array it seems to iterate without a problem, what am I missing?

`

def displayInventory(inventory):
  print("Inventory: ")
  item_total = 0
  for k, v in inventory.items():
    item_total  = v
    print(v, k)
  print("Total number of items: "   str(item_total))

def addToInventory(inventory, addedItems):
  items = []
  amount = []
  print(addedItems)
  for keys, values in inventory.items():
    items.append(keys)
    amount.append(values)

  for i in range(len(addedItems)):
    for j in range(len(inventory)):
     if addedItems[i] == items[i]:
      inventory[items[j]] =  1
     else:
        inventory.setdefault(addedItems[i], 1)

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

` Here is the error message

['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

<ipython-input-54-b83d92c005f4> in <module>
     26 inv = {'gold coin': 42, 'rope': 1}
     27 dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
---> 28 inv = addToInventory(inv, dragonLoot)
     29 displayInventory(inv)

<ipython-input-54-b83d92c005f4> in addToInventory(inventory, addedItems)
     19   for i in range(len(addedItems)):
     20     for j in range(len(inventory)):
---> 21      if addedItems[i] == items[i]:
     22       inventory[items[j]] =  1
     23      else:

IndexError: list index out of range

I tried testing index i in regular for loops and it iterated through the items without issue, I am not sure why it says out of range.

CodePudding user response:

def displayInventory(inventory):
    item_total = 0
    for k, v in inventory.items():
        item_total  = int(v)
        print(v, k)
    print("Total number of items: "   str(item_total))

def addToInventory(inventory, addedItems):
    items = []
    amount = []
    print(addedItems)
    for keys, values in inventory.items():
        items.append(keys)
        amount.append(values)
    for i in range(len(inventory)):
        for j in range(len(addedItems)):
            if addedItems[j] == items[i]:
                inventory[items[i]]  = 1
            else:
                inventory.setdefault(addedItems[i], 1)
    return inventory

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

CodePudding user response:

items will take ['gold coin', 'rope'], so len items is 2, the for loop is in range(len(addedItems)) that mean in range of 5:

tha loop will can compare items[0] and items[1] then the rest will be out of range of the list and lead to the error you have.

and your function addToInventory must return a result otherwhise you will get an error here :

for k, v in inventory.items():

because items will not be known by the function

  • Related