Why does list(my_list) modify the object?

后端 未结 2 1553
轻奢々
轻奢々 2020-12-11 18:52

I happened on this peculiar behaviour accidentally:

>>> a = []
>>> a[:] = [\'potato\', a]
>>> print a
[\'potato\', [...]]
>>         


        
相关标签:
2条回答
  • 2020-12-11 19:21

    The ... is only displayed when an item contains itself -- that is, the same object. list(a) makes a copy of the list, so the inner a isn't the same object. It only shows the ... when it gets to "a inside a", not "a inside list(a)".

    0 讨论(0)
  • 2020-12-11 19:27

    list() makes a shallow copy. The outer list is no longer the same object as the list it contains. It is printed as you would expect.

    0 讨论(0)
提交回复
热议问题