If slicing does not create a copy of a list nor does list() how can I get a real copy of my list?

Slicing creates a shallow copy. In your example, I see that you are calling insert() on item[-1], which means that item is a list of lists. That means that your shallow copies still reference the original objects. You can think of it as making copies of the pointers, not the actual objects.

Your solution lies in using deep copies instead. Python provides a copy module for just this sort of thing. You'll find lots more information on shallow vs deep copying when you search for it.


If you copy an object the contents of it are not copied. In probably most cases this is what you want. In your case you have to make sure that the contents are copied by yourself. You could use copy.deepcopy but if you have a list of lists or something similar i would recommend using copy = [l[:] for l in list_of_lists], that should be a lot faster.

A little note to your codestyle:

  • del is a statement and not a function so it is better to not use parens there, they are just confusing.
  • Whitespaces around operators and after commas would make your code easier to read.
  • list(alist) copies a list but it is not more pythonic than alist[:], I think alist[:] is even more commonly used then the alternative.

Tags:

Python

List

Copy