Z
Z
zhamkazz2021-10-14 00:14:45
Python
zhamkazz, 2021-10-14 00:14:45

How are matrices assigned?

An A-matrix in python, an empty
B-matrix in python, with data I
assign A=B,
I start changing the data in A and the data in B changes, what should I do to prevent this from happening and why does this happen?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2021-10-14
@zhamkazz

Why is this happening?

Because:
a = [1,2,3,5,6]
b = a
print(id(a))
print(id(b))
# 1552394418184
# 1552394418184

both A and B refer after assignment to the same object.
what to do to prevent this from happening

b = a.copy()
print(id(a))
print(id(b))
# 1552394980744
# 1552395031496

now they are two different objects

A
Antonio Solo, 2021-10-14
@solotony

import copy

b = copy.deepcopy(a)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question