2

Please what's the difference between this two codes in python:

white=[2,4,8,9]
black = white

and

white=[2,4,8,9]
black = white[:]

thank you so much.

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
user2563817
  • 993
  • 1
  • 6
  • 3
  • 4
    Try modifying white or black after the copy and see if the other changes. – John Zwinck Jul 13 '13 at 13:12
  • This article has been published recently and is exactly what you're looking for - http://nedbatchelder.com/text/names.html – Eli Bendersky Jul 13 '13 at 16:03
  • Does this answer your question? [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – smci Apr 18 '20 at 04:25

3 Answers3

8

The first copies a reference to the list white to the variable black

So any changes to black will also alter white and visa versa

Think of it as an alias or nickname for white

The second copies the contents of the list white to the variable black and is perhaps better written like this

black = list(white)

In this case there is no connection between the two variables black and white as it is the contents of white that are copied and not a reference to white itself.

Extra to take into account the relevant comment below (thanks Jon Clements): you can read more about deep copies vs shallow copies here Understanding dict.copy() - shallow or deep?

Community
  • 1
  • 1
Vorsprung
  • 32,923
  • 5
  • 39
  • 63
5

You can use id() and is to see the difference in Python shell:

>>> white=[2,4,8,9]
>>> black = white
>>> id(white)
41026064
>>> id(black)
41026064
>>> black is white
True

black and white point to the same object, so they are not two things, they are one. When you make a slice (or shallow) copy, a new object is created.

>>> white=[2,4,8,9]
>>> black = white[:]
>>> id(white)
41026064
>>> id(black)
41025904
>>> black is white
False
dansalmo
  • 11,506
  • 5
  • 58
  • 53
0

As an additional data point, Python 3.3 added the copy method as a readable alternative to the slicing syntax. So white.copy() also creates a shallow copy of the list white

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412