-1

I have an issue with writing data to a 2d array in a for loop. If I'm printing/plotting within the loop the values seems normal. While if I'm printing outside the loop, all rows in the array are equal. See attached screenshot. Do anyone have a suggest on how to prevent overwriting the values in the array?

import matplotlib.pyplot as plt
import math as mt
import numpy as np

I0=1 #
L=5 #[m] distance from slit screen to the observation screen
w=[668, 613, 575, 540, 505, 470, 425] #[nm] wavelengths
b=14 #[um] slit width

n=10 #length of array

x = np.linspace(-2*mt.pi,2*mt.pi, n)

bet=[[0.0]*n]*len(w) #beta
Ip=[[0.0]*n]*len(w) #intensity

fig,ax=plt.subplots()
ax2=ax.twinx()

# for 7 different wavelenths
for j in range(len(w)):
    # write to array
    for i in range(n):
        bet[j][i]=mt.pi*b/w[j]*mt.sin(x[i])
        Ip[j][i]=I0*(mt.sin(bet[j][i])/bet[j][i])**2
    ax.plot(x,bet[j])
    ax2.plot(x,Ip[j])
    print(Ip[j]) 
plt.show()

#to compare with the print within the loop
for k in range(len(w)):
    print(Ip[k]) #all rows is equal

Print/plot:

enter image description here

1 Answer 1

2

You have the problem with these lines:

bet=[[0.0]*n]*len(w) #beta
Ip=[[0.0]*n]*len(w) #intensity

It is because when you multiply a list of lists then the rows will point to exactly the same list.

You should change these two lines to:

bet=[[0.0]*n for _ in range(len(w))] #beta
Ip=[[0.0]*n for _ in range(len(w))] #intensity
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.