Unexpected output when adding items to list of lists in python
list, python
Solution
This is a classic Python pitfall.
c = [[]]*10
creates a list with 10 items in it. Each of the 10 items in the same exact list. So modifying one item modifies them all.
To create 10 independent lists, use
c = [[] for i in range(10)]
Problem
This is fairly straghtforward code and it isn't doing what I want it to do. What is wrong? ``` In [63]: c = [[]]*10 In [64]: c Out[64]: [[], [], [], [], [], [], [], [], [], []] In [65]: c[0] Out[65]: [] In [66]: c[0] += [1] In [67]: c Out[67]: [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]] ``` Expected output is `[[1], [], [], [], [], [], [], [], [], []]`.