0

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?

Edited by ErlendHL: each other

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by ErlendHL
0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.