3

The del statement in python, when applied to a list, does something very strange. It not only deletes the entry in the list in question, but also "backtracks" to delete the same element in whatever list the variable was derived from.

For instance:

>>> x
[1, 2, 3, 4, 5]
>>> z=x
>>> del z[1]
>>> z
[1, 3, 4, 5]
>>> x
[1, 3, 4, 5]

In other words, even though I apply delete to z, the deletion is also applied to x. This "backtracking" doesn't come up with any other commands or functions, e.g.

>>> x=[1,2,3,4,5]
>>> z=x
>>> z+[6]
[1, 2, 3, 4, 5, 6]
>>> x
[1, 2, 3, 4, 5]

applying the add function to z leaves x unaffected, as it very well should.

This is causing me all sorts of headaches with the delete 'NA' scrip that I'm working on. Do you know what's going on with the del statement, and how can I get around this problem so that if I set z=x and then apply del to z, x remains unchanged?

1

1 Answer 1

9

z = x does not make a copy of the list. z and x now point to the same list. Any modification of that list will be visible through both names, z and x.

With z + [6], you did not assign the result back to z. Try printing z after doing that. It will be unchanged, just like x.

z += [6] would be necessary to assign the result back to z and it would have the same behavior as your first example.

You can copy the list using one of these methods:

z = x[:]
z = list(x)
Sign up to request clarification or add additional context in comments.

6 Comments

Close, but there's an important distinction between z += [6] and z = z + [6] that you're missing.
@Miles What is the difference between z += [6] and z = z + [6]. Seems to be the same thing. Am I missing something?
@miki725: z += [6] is an in-place operation on the list. z + [6] creates a new list.
Right, so if z and x point to the same list, the former will update the list that both variables point to, while z = z + [6] will assign z to a new longer list and leave x pointing to the original list.
Thanks for the clarification, I should've known better!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.