qwertylpc
qwertylpc

Reputation: 2126

Python Append vs list+list

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

Upvotes: 0

Views: 190

Answers (1)

zondo
zondo

Reputation: 20366

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.

Upvotes: 2

Related Questions