0

I read Python list + list vs. list.append(), which is a similar question, but my question is more in relation to the code below

a = [[]] * 4
b = [[]] * 4
a[3] = a[3] + [1]
b[3].append(1)
print a, b

Which gives:

[[],[],[],[1]] [[1],[1],[1],[1]]

Why would these 2 be any different? I've never run into an example like this where these 2 methods have different outputs...

Thanks

Community
  • 1
  • 1
qwertylpc
  • 2,016
  • 7
  • 24
  • 34
  • http://stackoverflow.com/questions/36322067/the-meaning-of-on-list-in-python/36322093#36322093 There can be a major difference between creating vs modifying – Padraic Cunningham Apr 06 '16 at 00:41

1 Answers1

2

a[3] = a[3] + [1] is not modifying a[3]. Instead, it is putting a new item there. a[3] + [1] creates a list that is just like a[3] except that it has an extra one at the end. Then, a[3] = ... sets a at the index 3 to that new list.

b[3].append(1) accesses b[3] and uses its .append() method. The .append() method works on the list itself and puts a one at the end of the list. Since [[]] * 4 creates a list with four copies of another list, the .append() method reveals its changes in all items of b.

zondo
  • 19,901
  • 8
  • 44
  • 83