Don't understand python pop altering multiple variables
I'm sure this is something simple that I've ov开发者_运维知识库erlooked, but I'm hoping someone can explain the following to me:
origList = [1, 2, 3, 4, 5, 6, 7, 8]
def test(inputList):
while range(len(inputList)):
inputList.pop()
altList = origList
test(altList)
print 'origList:', origList # prints origList: []
print 'altList:', altList # prints origList: []
I thought I understood list.pop(), but what I don't understand is why the original list is modified if I'm only 'popping' the elements of the alternate list...
Everything in Python is a reference. They're the same list.
altList = origList[:]
It's because the line:
altList = origList
does not create a copy of the origList object. Both names, will refer to the same underlying object. To create a copy, see the copy module.
this is because when you say
altList = origList
you're actually pointing the location of altList to the location of origList (since everything in python is an object). effectively, equality here means "make these the same object" instead of give them the same values.
The "problem" is this line:
altList = origList
In Python, assignment of a list like this only performs a "shallow copy"; altList just becomes another reference to the data in origList, rather than being a completely new copy.
To get what you want, try
from copy import deepcopy
altList = deepcopy(origList)
精彩评论