11. Making a purchase, missing some logic


I already passed this exercise, but there is some logic I simply dont get.
Define a function compute_bill that takes one argument food as input.In the function, create a variable total with an initial value of zero.For each item in the food list, add the price of that item to total.Finally, return the total.

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 each in food:
        total += prices[each]
    return total

At "for each in food", let's say apple is the function argument, "each" does not have any value since "apple" is not a list itself, it just a key for a value inside another list, but I never implicit THAT in the function, so "each" at "for each in "apple"" doesnt have any value because apple is just a string unassociated with any list.
At prices[each] I'm passing the value assigned to the key "apple" as a key to the "prices" list, which is 2, which at the same time is not an available key. and still the function works.
My only guess is that the lists allow to use values in a reversed way, therefore, "2" calls serves as a key for "apple", but that kind of function may cause conflict in larger lists.
Can you guys explain it to me?


The for .. in will actually work with 'apple' (it will go through all the characters), but that's not the point here. You're expected to call the function with a list of foods, like the list shopping_list. The loop will then assign to each every value in the list (so first banana, then orange and the apple).
It will then add the price of each item to the total. To get the price, you are using the dictionary prices, of which you first get the element "banana", then "orange" and then "apple", which will give you the correct prices.


But isn't the exercise suppose to call the function with "apple" as argument, and not a list?


Calling the function with a list as argument makes everything clear. But still I thought the exercise was calling the function with a string, the output error I received before made me think that. I guess I got it wrong


It's a bit of a weird name, but in this case food, represents a list of food.


Yeah I think the name confused me.
Thanks for the answer pal.