1

I am trying to run the following code, energylist is a list of 2-dimensional arrays. I want to manipulate an element [k][i] in the 2-D arrays in energylist. This is done in the for loop with energylist[r][k][i]= (N1[s]*0.1+N2[t]*1).

N1 = xrange(0,4,1)
N2 = xrange(0,4,1)

V1 = arange(-20,20.1,10)
V2 = arange(-20,20.1,10)

energy = zeros((len(V2),len(V1)))
energylist=[]

for l in xrange(0,16,1):
    energylist.append(energy)

for i in xrange(0,len(V1),1):
    for k in xrange(0,len(V2),1):
        r=0
        for s in xrange(0,len(N1),1):
            for t in xrange(0,len(N2),1):
                energylist[r][k][i]= (N1[s]*0.1+N2[t]*1)
                r += 1

However, after running this, all of the arrays in energylist are the same, although obviously this is not reasonable as N1 and N2 have changed. The code works if I replace the line energylist[r][k][i]= (N1[s]*0.1+N2[t]*1) with

energy=array(energylist[r])
energy[k][i]= (N1[s]*0.1+N2[t]*1)
energylist[r]=array(energy)

What is wrong with my original code?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497

1 Answers1

0

The problem is in your line

energylist.append(energy)

Here you append only a REFERENCE to your only one existing energy array. Thus, you have only one array stored in memory, being referenced many times. If you modify this array anywhere, all pointers will point to the modified array. Your situation is not that you have many arrays with the same content - you have only one array with many references.

The solution would be:

for l in xrange(0,16,1):
    energylist.append(zeros((len(V2),len(V1))))

Here, you create an explicit new zeros array in each append, so you will get 16 arrays stored in memory which you can modify separately.

Community
  • 1
  • 1
leeladam
  • 1,748
  • 10
  • 15