1

I'm trying to initialize a bi-dimentional (3x3) list without typing all elements, since they are all the same.

However, it seems that only the first line of this matrix is really created as a new object, and the subsequent lines are just references to the first line.

How could I create all lines are independent objects?

Here's an example to illustrate this:

# Create a bi-dimentional list
a=[[''] * 3] * 3
print a
>>>[['', '', ''], ['', '', ''], ['', '', '']]

# change a single element, on first line
# notice that it will change also the elements at other lines
a[0][1] = 'x'
print a
[['', 'x', ''], ['', 'x', ''], ['', 'x', '']]
Alex
  • 633
  • 1
  • 10
  • 29

2 Answers2

5

You can use range():

a = [[''] * 3 for _ in range(3)]

Using * with list (and more generally with objects) actually just create references, you have to create new lists.

Delgan
  • 18,571
  • 11
  • 90
  • 141
0

you could do:

a = ['','','']
b = ['','','']
c = ['','','']

d = [a, b, c]

not sure it's what you're after, but d[0][1] = 'x' returns:

[['','x',''],['','',''],['','','']]

because even an assignment like a=b=c=[] just creates three references to the same object, and you end up with the same issue.

Stidgeon
  • 2,673
  • 8
  • 20
  • 28