0

Let's start with a list a:

>>> a = [1,2,3]
>>> id(a)
4511772616

I know we can use a[:] to create a copy of a:

>>> id(a[:])
4511794120

However, my question is: Why I can use a[:] to reassigns all of the contents of a without changing the address of it?

>>> a[:] = [1,2,3]
>>> id(a)
4511772616
>>> a
[1,2,3]

Also, if I wanna go deep to figure out what's under the hood, where should I start with? I tried to find some memory management materials about Python. However, it seems that they all rarely talk about the case of special syntax such as List comprehension and Slicing notation.

Tab
  • 347
  • 3
  • 14
  • 2
    Does this answer your question? [In python, what is the difference between slice with all the element and itself?](https://stackoverflow.com/questions/59849248/in-python-what-is-the-difference-between-slice-with-all-the-element-and-itself) Some more helpful links: [Mutable Sequence Types](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types), [Assignment statements](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements) [How assignment works with Python list slice?](https://stackoverflow.com/questions/10623302/how-assignment-works-with-python-list-slice) – Tomerikoo Jan 22 '20 at 22:20
  • @Tomerikoo disagree with the dupe target. This is all tangential to what, now that I think more about it, is kinda odd if you're not used to Python. `[:]` is syntax for both in-place and a shallow copy, depending on how it's used – roganjosh Jan 22 '20 at 22:27
  • @Tomerikoo yeah, I think the last link is the most useful. I didn't know a dupe target off the top of my head but you've shown me one, thanks :) – roganjosh Jan 22 '20 at 22:34
  • 1
    @roganjosh well the first dupe is even a dupe by itself so there goes another one :D – Tomerikoo Jan 22 '20 at 22:34
  • @roganjosh BTW in that second dupe I quoted, the second answer and not the accepted one is actually better – Tomerikoo Jan 22 '20 at 22:37
  • @Tomerikoo Thanks for the helpful links. And sorry for the duplicated question, I didn't found the right keyword to search. – Tab Jan 23 '20 at 03:55

0 Answers0