Difference between .remove() and del ? ("It’s Dangerous to go Alone!" exercise)


I'm at the exercise "It's Dangerous to go Alone!":

The code works fine for me if I follow the instructions, but conceptually I still find it quite confusing when should I use .remove to remove an entry and when to use del().
Here is my code (The other parts of the code is removed for clarity):

inventory = {
    'pouch' : ['flint', 'twine', 'gemstone'], 
    'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']

print "This is the inventory of backpack before dagger removal: ", inventory['backpack']
inventory['backpack'].remove('dagger')   #This removes dagger
print "\nThis is the inventory of backpack after dagger removal: ", inventory['backpack']

del inventory.backpack['bedroll'] #This should remove bedroll
print "\nThis is the inventory of the almost-empty backpack: ", inventory['backpack']

I try testing out both the del and .remove functions to remove one of the items inside a list which is the value of one key-value pair. The .remove version worked, but the del did not.
Error message:

Traceback (most recent call last):
File "python", line 12, in
AttributeError: 'dict' object has no attribute 'backpack'

Perhaps the del function is intended to delete an entry directly within the top list and not an entry which is bundled within it? Would simply like to build an intuition on which one to use.


remove() removes the first item it can find:

aList = ['a','b','c']
print aList

where as del deletes based on index:

bList = ['a','b','c']
del bList[0]
print bList


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.