Hi. I make a new array, p:

p=[[x]+[0]*(y)]*z

then if x=1, y=2 and z=3, the array is:

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

But now, the problem steps in. If I now say that p[0][0]=2, then the array is:

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

Why is all the 2nd dimensions refering to each other? How do I make a non-refering 2d array?

Recommended Answers

All 2 Replies

Because the syntax

p = [ expression ] * 3

evaluates the expression once and creates a list of 3 references to the result of this evaluation. You can use

p = [ expression for i in range(3) ]

to evaluate the expression thrice and put the results in a list.
Try

p = [[x] + [0] * y for i in range(z)]

Under python 2, you can use xrange instead of range to gain a little speed.

Thanks, it worked :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.