Why python list is not passed by reference -
i'm doing homework , assignment make script removes highest , lowest prices , prints middle price here code:
def removeall(list,value): list = [n n in list if n != value] print(list) prices = [] while true: usrinput = input('please enter price or stop 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 can make work like:
def removeall(list,value): mylist = [n n in list if n != value] return mylist prices = removeall(prices,highest)
but question why removeall() not changing prices? isn't passed reference?
python parameters not same references in other languages. it's more pointer that's being passed value. if modify pointer point else, calling code doesn't see change.
to make change can seen outside function, need modify list in place. simple way use slice assignment:
list[:] = [n n in list if n != value]
this changes existing list, rather rebinding list
variable. (note, that's bad variable name, since shadows builtin list
type. suggest avoiding local variable name!)
Comments
Post a Comment