0

I have a list of n elements, and I'm trying to make a new nxn array in which all the rows are the elements of my previous list (for example, if I have a list u=[a,b], then the array is y=[u,u]=[[a,b],[a,b]]) and for all the values of index i=1,2,... I want all the elements y[i][i] to be added with additional values h (that is, if the list is p=[a,b], then the final product is q=[p,p]=[[a+h,b],[a,b+h]]).

If I made the program to be straightforward like this

u=[[1,2],[1,2]]
h=1e-3
for i in range(2):
  u[i][i]+=1
print(u)

it would print out what I want correctly

[[2, 2], [1, 3]]

but if I did it in a loop like this

x=[1,2]
u=[]
h=1e-3
for i in range(len(x)):
  u.append(x)
for i in range(2):
  u[i][i]+=1
print(u)

the program would assume that I'm trying to add 1 to each of its elements like this

[[2, 3], [2, 3]]

I did check "u" before adding 1 to its u[i][i] elements with the second code and it prints out u=[[1,2],[1,2]] as well. So what did I do wrong here?

1 Answer 1

1
x=[1,2]
u=[]
h=1e-3

for i in range(len(x)):
  u.append(x.copy())

for i in range(2):
  u[i][i] +=1

print(u)

You got almost there! In fact, when you append x to u twice, you make "linked twins". Which means: x stays in in u. And you have x twice. If you modify u[0] which is x, then you modify u[1] which is also x.

To avoid that, use x.copy().

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.