Why does list(my_list) modify the object?

2020-02-07 02:33发布

I happened on this peculiar behaviour accidentally:

>>> a = []
>>> a[:] = ['potato', a]
>>> print a
['potato', [...]]
>>> print list(a)
['potato', ['potato', [...]]]

By what mechanism does calling list(a) unroll one level of recursion in the string representation of itself?

2条回答
一纸荒年 Trace。
2楼-- · 2020-02-07 03:23

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.

查看更多
▲ chillily
3楼-- · 2020-02-07 03:34

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)".

查看更多
登录 后发表回答