Radostin Slavov
Radostin Slavov

Reputation: 49

Why python list is not passed by reference

I'm doing a homework and my assignment is to make a script that removes highest and lowest prices and prints the middle price here is my code:

def removeall(list,value):
    list = [n for n in list if n != value]  
    print(list)
prices = []

while True:
    usrinput = input('Please enter price or stop to stop: ')
    if usrinput == 'stop':
        break

    prices.append(float(usrinput))


print(prices)

highestprice = max(prices)
lowestprice = min(prices)

removeall(prices, highestprice)
removeall(prices, lowestprice)

print(prices)

print(sum(prices)/len(prices))

I know that I can make it work like:

def removeall(list,value):
    mylist = [n for n in list if n != value]  
    return mylist

prices = removeall(prices,highest)

But my question is why removeall() is not changing prices? Isn't it passed by reference?

Upvotes: 0

Views: 69

Answers (2)

Blckknght
Blckknght

Reputation: 104712

Python parameters are not really the same as references in some other languages. It's more like a pointer that's being passed by value. If you modify the pointer to point to something else, the calling code doesn't see the change.

To make a change that can be seen outside the function, you need to modify the list in place. A simple way to do that is to use a slice assignment:

list[:] = [n for n in list if n != value]

This changes the existing list, rather than just rebinding the list variable. (Note, that's a very bad variable name, since it shadows the builtin list type. I strongly suggest avoiding it as a local variable name!)

Upvotes: 2

Douglas Leeder
Douglas Leeder

Reputation: 53310

Your removeall function isn't altering the list being passed in, it is creating a new list, printing it out then throwing it away.

Upvotes: 0

Related Questions