Passing in a list as an argument creates a copy of that list?


#1

I was getting some weird error about apple returning as 7.5 and not 2, but when I ran this in another IDE it was fine. I looked through these forums and saw some people using
for i in food:
total += price[i]
instead of what I was using which was
for i in shopping_list:
total += price[i]

Does python make a copy of the list when passing it in as an argument to a function?


#2

Hi @mepda,

While I am not entirely sure what's going on under the hood and if python end up working off a copy when passing a list as an argument to a function but what I know is that in your code, you are refefring to the shopping_list regardless of what item is passed as argument. This means you couldn't possibly reuse your function and pass another argument to it, it would always loop through shopping_list and would throw an error if shopping_list doesn't exist or is unreachable...

This is why the proper way is to refer to the name of the argument like so:

def compute_bill(food):
    total = 0
    
    for item in food:
        if stock[item] > 0:
            total += prices[item]
            stock[item] -= 1
    return total

This is an example that demonstrate what I'm explaining:

shopping_list = ["banana", "orange", "apple"]
another_shopping_list = ["orange", "apple", "pear"]

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}
    
prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}

# Write your code below!
def right_compute_bill(food):
    total = 0
    
    for item in food:
        if stock[item] > 0:
            total += prices[item]
            stock[item] -= 1
    return total


def wrong_compute_bill(food):
    total = 0
    
    for item in shopping_list:
        if stock[item] > 0:
            total += prices[item]
            stock[item] -= 1
    return total


print "Calling right_compute_bill function on the two lists"
print right_compute_bill(shopping_list)             # will print 5.5 as expected
print right_compute_bill(another_shopping_list)     # will print 4.5 as expected


print "Calling wrong_compute_bill function on the two lists"
print wrong_compute_bill(shopping_list)             # will print 5.5
print wrong_compute_bill(another_shopping_list)     # will also print 5.5!

Hope this helped! :smile: