9

Are these two expressions the same?

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

The resulting a and b values look the same. But would one way be better than the other? What is the difference here.

1
  • 4
    There are literally thousands questions covering this exact topic... Commented Jan 5, 2012 at 19:53

3 Answers 3

18

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.

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

3 Comments

I was typing the exact same thing. +1 to you.
yup, in the first one, all three arrays are the same object. If you use integers instead for example [1]*5 instead of [[]]*5, a new integer is used in each position
these are not python arrays...these are python lists.
7

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]]

1 Comment

+1. Try a[0].append("foo").
0

It's a classic case of shallow-copy vs deep copy, as explained here in the Python docs :)

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.