Adam
Adam

Reputation: 3

For Loop Append to list from another

I'm working on a "pick up all" and "drop all" for a game I'm designing. The player has an inventory (inventory) and each room has it's own to keep track of what is in it. When it is a specific item, I can easily append or remove the item from the respective lists, but when it is for them all, I am not sure how to proceed. (NOTE: I won't know how many items are in the inventories as it will change as players take and drop items)

ROOMNAMEinventory = ['lamp', 'coin']
inventory = ['string']
do = raw_input("What would you like to do?").upper()
if(do == 'drop all'):
  for items in ROOMNAMEinventory:
    inventory.append(items)
    ROOMNAMEinventory.remove(items)
print inventory
print ROOMNAMEinventory

Currently, this prints out:

['string', 'lamp']
['coin']
None

Why does it print the None?

Upvotes: 0

Views: 111

Answers (2)

ElmoVanKielmo
ElmoVanKielmo

Reputation: 11315

List in Python supports adding one to another:

roomname_inventory = ['lamp', 'coin']
inventory = ['string']
do = raw_input("What would you like to do?").upper()
if (do == 'DROP ALL'):
    inventory += roomname_inventory
    roomname_inventory = []
print inventory
print roomname_inventory

But if you just want to get rid of modifying the list while iterating over it, you could also do:

if (do == 'DROP ALL'):
    while roomname_inventory:
        inventory.append(roomname_inventory.pop(0))

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140286

2 mistakes here

  1. you convert to uppercase but test against lower!
  2. you should iterate on a copy of ROOMNAMEinventory, modifying list while iterating on it is not recommended: it changes lists to that ['string', 'lamp'] and ['coin']: not that you want

Fixed code:

ROOMNAMEinventory = ['lamp', 'coin']
inventory = ['string']
do = raw_input("What would you like to do?").upper()
if(do == 'DROP ALL'):  # upper vs upper: could work :)
  for items in ROOMNAMEinventory[::]:  # iterate on a copy of the list
    inventory.append(items)
    ROOMNAMEinventory.remove(items)
print inventory
print ROOMNAMEinventory

result (when inputting drop all)

['string', 'lamp', 'coin']
[]

Upvotes: 0

Related Questions