Python list([]) and []

list(chain) returns a shallow copy of chain, it is equivalent to chain[:].

If you want a shallow copy of the list then use list(), it also used sometimes to get all the values from an iterator.

Difference between y = list(x) and y = x:


Shallow copy:

>>> x = [1,2,3]
>>> y = x         #this simply creates a new referece to the same list object
>>> y is x
True
>>> y.append(4)  # appending to y, will affect x as well
>>> x,y
([1, 2, 3, 4], [1, 2, 3, 4])   #both are changed

#shallow copy   
>>> x = [1,2,3] 
>>> y = list(x)                #y is a shallow copy of x
>>> x is y     
False
>>> y.append(4)                #appending to y won't affect x and vice-versa
>>> x,y
([1, 2, 3], [1, 2, 3, 4])      #x is still same 

Deepcopy:

Note that if x contains mutable objects then just list() or [:] are not enough:

>>> x = [[1,2],[3,4]]
>>> y = list(x)         #outer list is different
>>> x is y          
False

But inner objects are still references to the objects in x:

>>> x[0] is y[0], x[1] is y[1]  
(True, True)
>>> y[0].append('foo')     #modify an inner list
>>> x,y                    #changes can be seen in both lists
([[1, 2, 'foo'], [3, 4]], [[1, 2, 'foo'], [3, 4]])

As the outer lists are different then modifying x will not affect y and vice-versa

>>> x.append('bar')
>>> x,y
([[1, 2, 'foo'], [3, 4], 'bar'], [[1, 2, 'foo'], [3, 4]])  

To handle this use copy.deepcopy.

Leave a Comment