what is the difference between a = x and a=x[:] in python [duplicate]

风流意气都作罢 提交于 2020-11-29 03:10:25

问题


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


回答1:


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




回答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



回答3:


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]
>>> 


来源:https://stackoverflow.com/questions/20586230/what-is-the-difference-between-a-x-and-a-x-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!