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

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.