0

I was writing a function to return a 2D array full of random numbers, and after looking at the doc for random, I came up with this:

def get2D(arr, mu, sigma, randfunc):
x = 0
for i in arr:
    get1D(arr[x], mu, sigma, randfunc)
    x += 1
return arr

def get1D(arr, mu, sigma, randfunc):
    x = 0
    for i in arr:
        arr[x] = randfunc(mu, sigma)
        x += 1

And after a bit of looking around to see if I can initialize an array of a specific shape without numpy (nothing against numpy, just to see if I can reduce the number of dependencies) I found this:

[[0]*2]*2

But when I run the function using the above, I end up with unique numbers in the inner most dimensions but everything after that are repetitions. e.g. [[1,2],[1,2]]

Since I don't have much of a theoretical understanding in python, I was just shooting in the dark. That was a reason why I used for loops instead of list comprehensions; I was trying to prevent bugs caused by my limited understanding of python.

To check if I messed something up with the function pointers or something, I tried using numpy.empty() as input, and the function worked fine.

From that I'm guessing I created some sort of internal linking when I initialized the zero array. Just to check, I tried with 3D arrays, and got the sme results. e.g. [[[1,2],[1,2]],[[1,2],[1,2]]]

But I can't figure out why [0]*2 returns a zero array of items that are not linked to each other, but [0,0]*2 returns a whole bunch of linked items.

dare0021
  • 583
  • 6
  • 13
  • 1
    This is answered a bunch of places ... Basically `[whatever] * n` gives you a list with `n` references to `whatever`. With objects like `0` (which are immutable), this isn't a problem. It _is_ a problem with mutable objects however (like `[0]`) because when you mutate the object, all of the references in the list see it (because that's how references work ... sort of by definition I guess...) – mgilson Dec 08 '16 at 00:06

1 Answers1

1

just use a comprehension ... theres probably a duplicate around here somewhere

[[0]*2 for _ in range(N_LISTS)]

as to why its like this [[0]*2]*2 can be rewritten as follows

x = [0]*2 
y = [x]*2 # each internal is still the same "x"
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179