0

Why in the following example is appending to the big_l in the for loop changes also the last lists already added to the big_l?

l=[1,2,3,4,5]

big_l=[]

def f(ll):
    x=ll.pop(0)
    ll.append(x)
    return ll

for i in range(4):
    big_l.append(l)
    print l,big_l
    l=f(l)

It prints:

[1, 2, 3, 4, 5] - [[1, 2, 3, 4, 5]]
[2, 3, 4, 5, 1] - [[2, 3, 4, 5, 1], [2, 3, 4, 5, 1]]
[3, 4, 5, 1, 2] - [[3, 4, 5, 1, 2], [3, 4, 5, 1, 2], [3, 4, 5, 1, 2]]
[4, 5, 1, 2, 3] - [[4, 5, 1, 2, 3], [4, 5, 1, 2, 3], [4, 5, 1, 2, 3], [4, 5, 1, 2, 3]]
  • You are appending a reference to list. Since list is _mutable_ and all objects in `big_l` points to same list, changes will propagate across all elements of `big_l`. – Łukasz Rogalski Jun 06 '16 at 21:18
  • Possible duplicate of [Python list of lists, changes reflected across sublists unexpectedly](http://stackoverflow.com/questions/240178/python-list-of-lists-changes-reflected-across-sublists-unexpectedly) – ayhan Jun 06 '16 at 21:18
  • What are you expecting should occur? – Marcel Wilson Jun 09 '16 at 13:58

0 Answers0