Hi all,

Here's my issue:

>>> a = [1,2,3] #all good so far
>>> b = a #make a copy of a, called b
>>> b.remove(1) #remove value 1 from b ONLY
>>> print a #grrr, value has also been removed from a
[2, 3]
>>> print b #and b!
[2, 3]

Here's how I got around it:

>>> a = [1,2,3]
>>> b = []
>>> b.extend(a)
>>> b.remove(1)
>>> print a
[1, 2, 3]
>>> print b
[2, 3]

I was just wondering if anybody knew the reason behind this behavior, and if there is a more elegant way to accomplish the same thing. What does = really mean in Python?

8 Years
Discussion Span
Last Post by zachabesh

"=" means they are equal, i.e. the same memory address, so when you change one, you change the memory that they both point to. You can instead use:
a = [1,2,3]
b = a[:] ## copy all of the elements in "a" to a new block of memory
Also, there is copy and deepcopy depending on whether or not the list is nested. See here http://docs.python.org/library/copy.html Google will of course yield more copy and deepcopy examples if you decide to go that way.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.