I am trying to learn Python. Can someone please help me understand the difference between following two: a = x vs a=x[:]
Asked
Active
Viewed 5,420 times
1
-
hint: what does `a.slice(0)` do in javascript? – John Dvorak Dec 14 '13 at 17:36
-
1Impossible 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 Answers
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
-
-
-
-
@JBernardo There's no way to mutate tuples to begin with, so there wouldn't be any point to making a copy. Yes different underlying implementation but it gives you the same results anyhow (apart from id(), true) – Voo Dec 14 '13 at 19:26
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