Note that there are some explanatory texts on larger screens.

plurals
  1. POelements being copied along a list in python
    text
    copied!<p>I have a list of lists called <code>hab</code> acting as a 2D array. In this list of lists I am storing elements of a class called <code>loc</code> which is why I am not using a numpy array (it's not storing numbers). </p> <p>I want to fill each element with a randomly picked 'loc' by looping through each element. However it seems that whenever I get to the end of a row, the program takes the final row element and puts it in all the other elements in that row. This means that I end up with the list of lists looking like this:</p> <pre><code>3 3 3 3 3 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 4 4 4 4 4 </code></pre> <p>when actually I want all these numbers to be random (this is printing out a specific trait of each <code>loc</code> which is why it is numbers). </p> <p>Here is the relevant bit of code:</p> <pre><code>allspec=[] # a list of species for i in range(0,initialspec): allspec.append(species(i)) # make a new species with new index print 'index is',allspec[i].ind, 'pref is', allspec[i].pref hab=[[0]*xaxis]*yaxis respect = randint(0,len(allspec)-1) for j in range(0,yaxis): for k in range (0,xaxis): respect=randint(0,len(allspec)-1) print 'new species added at ',k,j,' is ', allspec[respect].ind hab[k][j]=loc(k,j,random.random(),allspec[respect]) print 'to confirm, this is ', hab[k][j].spec.ind for k in range (0,xaxis): print hab[k][j].spec.ind printgrid(hab,xaxis,yaxis) print 'element at 1,1', hab[1][1].spec.ind </code></pre> <p>Within the loop, I am confirming that the element I have created is what I want it to be with the line <code>print 'to confirm, this is ', hab[k][j].spec.ind</code> and it is fine at this point. It is only when that loop is exited that it somehow fills every element on the row with the same thing. I don't understand!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload