Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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


Solution 2:

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.


Post a Comment for "Why Does List(my_list) Modify The Object?"