-2

Let's say I do:

>> a = [1, 2, 3]
>> b = a[:] 
>> a[0] = 0
>> b
[1, 2, 3]

The statement b = a[:] clearly created a list b holding copies of the (potentially many) references that were also held by a. But the = operator only binds names and increase reference counts, so does the : operator create copies of references in Python? If so, when it comes to accessing lists, is that unique to the : operator? (e.g. indexing alone does not do that?)

Josh
  • 11,979
  • 17
  • 60
  • 96
  • 1
    No because the copying was already done by `a[:]`. The `=` did not do the copying, it just made `b` point to the new copy – rdas Apr 28 '20 at 16:32
  • All that an assignment does to give an object an additional name and increase the reference count of the object. – blhsing Apr 28 '20 at 16:33
  • @rdas Thanks - I haven't been able to find any material indicating that slices create copies of references in Python (if you have any please let me know) but that would make sense. – Josh Apr 28 '20 at 16:36
  • Does this answer your question? [Slicing a list in Python without generating a copy](https://stackoverflow.com/questions/5131538/slicing-a-list-in-python-without-generating-a-copy) – mkrieger1 Apr 28 '20 at 21:13
  • Thanks @mkrieger1 - Yes it does. Sorry, I initially thought the assignment operator was doing the copying, and was then later reminded that it never copies anything (first comment from @rdas), which helped me find the questions that I included below and that you just linked above as well. TL;DR yes, that answers the question, so we can definitely mark this as a duplicate and close accordingly (I just voted for it). Thanks again. – Josh Apr 28 '20 at 21:35

1 Answers1

0

Yes, the slice operator provides copies of the references, not views. See e.g.

Josh
  • 11,979
  • 17
  • 60
  • 96