Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected output when adding items to list of lists in python [duplicate]

Tags:

python

list

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

like image 824
Pratik Deoghare Avatar asked Jan 14 '23 14:01

Pratik Deoghare


1 Answers

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)]
like image 64
unutbu Avatar answered Jan 29 '23 18:01

unutbu