array of arrays question

M

Meo

Hi,

Here is what I'm doing in python 2.4.1 :
aOfa=[[[]]*3]*4
aOfa [[[], [], []], [[], [], []], [[], [], []], [[], [], []]]
aOfa[3][2].append(1)
aOfa
[[[1], [1], [1]], [[1], [1], [1]], [[1], [1], [1]], [[1], [1], [1]]]

Ok, so there is something I didn't understand about python's arrays.

The result I was expecting was :

[[[], [], []], [[], [], []], [[], [], []], [[], [], [1]]]

Somebody understand what's going on here?

Thank
 
P

Paul Rubin

Meo said:
Somebody understand what's going on here?

Yes, []*3 gives you three references to the same empty list, not three
separate empty lists. You need something like

[[] for i in xrange(3)]

to get separate lists.

Another example:

a = [1,2,3]
b = a
a[0] = 5
print b # prints [5,2,3]

Do you understand now?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,266
Messages
2,571,318
Members
47,998
Latest member
GretaCjy4

Latest Threads

Top