Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

python - Why does list(my_list) modify the object?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...