4

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], [], [], [], [], [], [], [], [], []].

Pratik Deoghare
  • 35,497
  • 30
  • 100
  • 146

1 Answers1

9

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)]
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677