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?
List in python is mutable types which means it can be changed after assigning some value. The list is similar to arrays in other programming languages.
Every element of the list turns to the newly appended element. For example, after 4 squares of the maze, the 4 elements in past are changed to whatever the appended element is.
Lists can contain any arbitrary objects. List elements can be accessed by index. Lists can be nested to arbitrary depth. Lists are mutable.
append() adds a list inside of a list. Lists are objects, and when you use . append() to add another list into a list, the new items will be added as a single object (item).
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)
".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With