It's Dangerous to Go Alone! Take This:The last line code


Why the code of last line can not be like this?


instead of

inventory['gold'] += 50

inventory = {
    'gold' : 500,
    'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
    'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']

# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']

# Sorting the list found under the key 'pouch'

# Your code here
inventory['pocket'] = ['seashell', 'strange berry', 'lint']
inventory['gold'] += 50


It won't be so because you need to add 50 to 500 and not place/append 50 to a list.

Append works like this:

x = [2, 3]
x.append([4, 5])
print (x)
OUTPUT: [1, 2, 3, [4, 5]]

whereas, inventory['gold'] += 50 will go ahead to change the value of the key gold to 550 (500+50).

If you print inventory['gold'] you will see what happened.

Hope this helps! :slight_smile:


This line assumes that inventory['gold'] is a list, when it is not. It is a value. And to this we wish to add 50.



why is it:

inventory["gold"] += 50

and not:

inventory["gold"] + 50

what does the "=" do?

thank you,


It perfoms a concurrent assignment when combined with an arithmetic operator.

inventory['gold'] + 50

is an expression that does not modify the value of the 'gold' member. We would need at a minimum to write,

inventory['gold'] = inventory['gold'] + 50

to make the modification. Expression on the right, object on the left, and assignment operator in between.


completes both in a single step (hence, concurrent).

inventory['gold'] += 50
print inventory['gold']     # 550


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