简体   繁体   中英

Why does the square matrix change when I loop through it?

When I loop thru a matrix to get the diagonals:

a = [[11, 2, 4],
     [4, 5, 6],
     [10, 8, -12]]

i = 0
o = 0
for a[i] in a:
    d1 = a[i][o]
    o += 1
    print(d1)

the output is like expected 11, 5, -12 ,
but when I print out the matrix again:

print(a)

the matrix changed

[[10, 8, -12], [4, 5, 6], [10, 8, -12]]

the first row is no more like it was [11, 2, 4] .

I can't figure out why is that happening.

Assuming your list of lists represents a square matrix, use a single loop inside a list comprehension to extract diagonals:

>>> [a[i][i] for i in range(len(a))]
[11, 5, -12]

I'm not sure where you came across this for a[i] in a syntax, but that does not do what you think it does. It ends up reassigning the 0th element to whatever the for loop is iterating over as a side effect, so don't do it.

Incidentally, fixing your code, it would be:

d = []
for i in range(len(a)):
    d.append(a[i][i])

Which is just an explicit re-writing of the list comprehension above.

You are assigning each element of a to the first element of a. See the following code.

for a[0] in a:
    print(a)

This yields:

[[11, 2, 4], [4, 5, 6], [10, 8, -12]]
[[4, 5, 6], [4, 5, 6], [10, 8, -12]]
[[10, 8, -12], [4, 5, 6], [10, 8, -12]]

a[0] is first reassigned to [11,2,4], then to [4,5,6], then finally to [10,8,-12]. a[1] and a[2] are unchanged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM