What is the importance of brackets?



shopping_list = [“banana”, “orange”, “apple”]

stock = {
“banana”: 6,
“apple”: 0,
“orange”: 32,
“pear”: 15

prices = {
“banana”: 4,
“apple”: 2,
“orange”: 1.5,
“pear”: 3

def compute_bill(food):
total = 0
for i in prices:
if food == i:
total += prices[i]
return total

print compute_bill(“apple”)

Write your code below!

<Below this line, add a link to the EXACT exercise that you are stuck at.>
<In what way does your code behave incorrectly? Include ALL error messages.>
Oops, try again. compute_bill([‘apple’]) returned 0 instead of 2
<What do you expect to happen instead?>
Once I added brackets into my input for the function compute_bill, the code returned zero instead of two like it was supposed to and like it did when there were no brackets in the input for the variable food

Replace this line with your code. 


Brackets denote an object in the List class. ['apple'] is a list with one element. "apple" is a string with 5 characters. It is iterable, but it is not treated as a list.

When we iterate over a string,

    for i in 'apple':

The iterator variable is a single letter in each iteration. a, then, p, and so on. We won’t find any keys in our dictionaries with those names.

When we iterate over a list,

    for i in ['apple']:

the iterator variable is ‘apple’, for which there is a matching key name in the dictionaries.

Consider the following:

def compute_bill(food):
    total = 0
    for i in food:
        total += prices[i]
    return total

Now compute_bill(['apple']) will return 2.