0
a = [0,1,2,3,4]

b = a
c = a[:]
d = list(a)

What's the difference for the three assignments? When shall I use [:]?

Nouman
  • 6,947
  • 7
  • 32
  • 60
kinder chen
  • 1,371
  • 5
  • 15
  • 25
  • `a[:]` or `list(a)` perform a shallow copy. – Jean-François Fabre Aug 09 '19 at 18:43
  • People who are more knowledgable please correct me if I am wrong but, the difference is that when you do a shallow copy you are actually using the same underlining array of data so if you change the copy you change the original as well. While deep copy creates a completely different array so changing it does not affect the original. shallow copy is like giving you a copy of the house's address for you to access it while deep copy is like making a completely identical house. – kkawabat Aug 09 '19 at 18:53
  • What is the difference for the two shallow copy? When shall I use `[:]` generally? – kinder chen Aug 09 '19 at 18:59
  • Just to make it clear, `b = a` is not shallow nor a deep copy. What you are doing there is just assign the reference to the same in-memory list to both variables `a` and `b`. A shallow copy is when you create new in-memory copies of all elements in `a` but you don't create a new copy for any referenced objects that `a` may contain (that is what `a[:]` and `list[a]` do). For further reference: https://docs.python.org/2/library/copy.html – Leafar Aug 09 '19 at 19:15
  • @kkawabat no, with a shallow copy, you create *a new underlying array* (or list object, really, but yes, a whole new buffer underneath the hood) but that list contains the same objects as the list being copied. A deep copy recursively copies all the objects in the container/object as well. – juanpa.arrivillaga Aug 09 '19 at 19:20

0 Answers0