Nested Lists Assignment Problem

T

tiksin

Le Mercredi 26 Avril 2006 10:13, Licheng Fang a écrit :
I wanna use nested lists as an array, but here's the problem:

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

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

Could anybody please explain to me why three values were change? I'm
bewildered. Thanks!

I guess is a probleme of reference. Write that instead:
l = [ [0]*3 for i in xrange(3) ]

cordialement,
 
F

Fredrik Lundh

Licheng Fang said:
But I still wonder why a nested assignment "a = [[0]*3]*3" generates 3
references to the same list, while the commands below apparently do
not.

that's because they're replacing a list item, rather than modifying it.
a = [0] * 2
a [0, 0] <- now you have two references to the same integer.
a[0] = 1 <- now you've *replaced* the first integer with another integer.
a
[1, 0]

if you do the same thing with lists, it behaves in exactly the same way:
a = [[0]*3]*3
a [[0, 0, 0], [0, 0, 0], [0, 0, 0]] <-- three references to the same list
a[0] = [1, 2, 3] <-- replace the first list
a
[[1, 2, 3], [0, 0, 0], [0, 0, 0]]

however, if you modify the *shared* object, the modification will of course
be visible everywhere that object is used:
a[1][0] = "hello" <-- modified the first item in the shared list
a
[[1, 2, 3], ['hello', 0, 0], ['hello', 0, 0]]

</F>
 
D

Deepan Chakravarthy

Hello,
I had used pyumlgraph to generate dot files for single python script. Is
it possible to use pyumlgraph to generate dot files for multiple python
scripts ??? Or is it automatically done if i generate a dot file for the
final python script that imports all other files?

Thanks
Deepan Chakravarthy N
www.codeshepherd.com
 
G

Gary Herron

Licheng said:
Dennis Lee Bieber wrote:


Thank you very much!

But I still wonder why a nested assignment "a = [[0]*3]*3" generates 3
references to the same list, while the commands below apparently do
not.
It's got nothing to do with "nested"-ness. If X is ANY object in
Python, then [X]*3 will make a list with three references to X. If
you don't want three references to the single object X (and you don't),
then you have to find a different way to create three separate objects.
The copy module helps with this in some cases, but for your simple
example, you just want to create the three inner objects by evaluating
the expression [0]*3 three times. Here's several ways:

a = []
for i in range(3):
a.append([0]*3)

or

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

Clear?

Gary Herron
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top