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

#1

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

inventory['gold'].append(50)

inventory['gold'] += 50

``````inventory = {
'gold' : 500,
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
}

# 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'
inventory['pouch'].sort()

inventory['pocket'] = ['seashell', 'strange berry', 'lint']
inventory['backpack'].sort()
inventory['backpack'].remove('dagger')
inventory['gold'] += 50``````

#2

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!

#3

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`.

#4

hello,

why is it:

inventory["gold"] += 50

and not:

inventory["gold"] + 50

what does the "=" do?

thank you,

#5

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``````

#6

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