Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 457
wim Avatar asked Nov 01 '13 19:11

wim


People also ask

Why is my list changing in Python?

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.

Does append modify the list?

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.

Are nested lists mutable?

Lists can contain any arbitrary objects. List elements can be accessed by index. Lists can be nested to arbitrary depth. Lists are mutable.

Can we append a list to a list?

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


2 Answers

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

like image 119
BrenBarn Avatar answered Nov 14 '22 23:11

BrenBarn


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.

like image 36
kindall Avatar answered Nov 15 '22 00:11

kindall