1

I am trying to learn Python. Can someone please help me understand the difference between following two: a = x vs a=x[:]

Supertech
  • 746
  • 1
  • 9
  • 25
  • hint: what does `a.slice(0)` do in javascript? – John Dvorak Dec 14 '13 at 17:36
  • 1
    Impossible to tell unless you say what `a` is. For tuples both are the same thing – JBernardo Dec 14 '13 at 17:44
  • @JBernardo I think you mean "[...] what `x` is". That is true, though for most well behaved types (including tuples, that a shallow copy does nothing is just an optimization) its behaviour is identical to the list case, modulo fooling around with `id()`/`is`. –  Dec 14 '13 at 18:35

3 Answers3

8

a = x creates a reference:

a = [2]
x = a
print id(a)
print id(x)

Produces:

39727240
39727240

So if you alter a then x would change too because they are the same objects

Whereas

a = x[:] creates a new object

a = [2]
x = a[:]
print id(a)
print id(x)

Produces:

41331528
39722056

But over here changing a doesn't alter x because they are different objects

K DawG
  • 13,287
  • 9
  • 35
  • 66
2
In [648]: b = a

In [649]: b[0] = 2

In [650]: a  
Out[650]: [2]  <- a also changed

In [651]: b = a[:] <- Creating new object

In [652]: b[0] = 3

In [653]: b  
Out[653]: [3]

In [654]: a  
Out[654]: [2] <- a did not change
M4rtini
  • 13,186
  • 4
  • 35
  • 42
2

Trying to explain:

>>> x = [1,2,3]
>>> a = x
>>> # a is reference to x - a[0] and x[0] are same variable
>>> a[0] = 4 # same as x[0]...
>>> print x # proof
[4, 2, 3]
>>> a = x[:] # a is copy of x
>>> a[2] = 5 # a[2] is not x[2]
>>> print x
[4, 2, 3]
>>> print a
[4, 2, 5]
>>> 
Guy Dafny
  • 1,709
  • 1
  • 14
  • 25