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?

Recommended Answers

All 2 Replies

"=" 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.

Very interesting. Thanks. I'll keep this in mind.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.