Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list comprehension: creating 2d array [duplicate]

Possible Duplicate:
Python 2D list has weird behavor when trying to modify a single value

folks,

I am wondering if the two following statements are the same?

a = [[0]*3]*3
b = [[0]*3 for i in range(3)]

The results look the same. But would one way be better than the other? What is the difference here.

Thanks very much for your help.

nos

like image 828
nos Avatar asked Jan 05 '12 19:01

nos


2 Answers

No they are not.
In the first one you have (a list of) 3 identical lists, same reference, in the second you have three different lists

>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0]=1

>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]


>>> b = [[0]*3 for i in range(3)]
>>> b
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> b[0][0] = 1

>>> b
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
like image 38
joaquin Avatar answered Oct 20 '22 05:10

joaquin


They're not the same

>>> a[1][2] = 5
>>> a
>>> [[0, 0, 5], [0, 0, 5], [0, 0, 5]]


>>> b[1][2] = 5
>>> b
>>> [[0, 0, 0], [0, 0, 5], [0, 0, 0]]

The first one creates an outer array of pointers to a single inner array while the second actually creates 3 separate arrays.

like image 198
Charles Ma Avatar answered Oct 20 '22 04:10

Charles Ma