When does the slicing operator create a shallow copy in Python?

I would like to ask you for help with the behavior of the slicing operator in Python.

  • On the one hand, we know what L[:] creates a shallow copy of the list L. To verify this, you can simply print it out id(L), id(L[:]) and note that they are different.
  • On the other hand, we know that del L[:] removes links from the original object. This makes the original list empty, not a shallow copy of it. Of course, I agree that creating a shallow copy and then deleting links from it will make little sense, so I understand that here we want to work with the original list.

Is there a rule saying that the cutting operator creates a shallow copy, and when not? How can I find out without checking it manually?

I searched this and found the following topics:

but, unfortunately, they do not answer my question, at least I do not see this.

+4
source share
1 answer

del L[:]- This is a great operation from access to L[:], which again is a separate operation from L[:] = x.

  • del L[:]calls an __delitem__object with an object slice.
  • L[:]calls __getitem__with this sliceobject.
  • L[:] = xcalls __setitem__with sliceand x.

-, , . __delitem__ , , __setitem__ , __getitem__ () , .

. , NumPy array, __getitem__ , - .

+5

Source: https://habr.com/ru/post/1629038/


All Articles