F
F
Fisab2016-01-07 17:08:43
Python
Fisab, 2016-01-07 17:08:43

In python, when assigning one array to another, they are equal, how to make them independent?

>>> b = [1,2]
>>> a = b
>>> a[0]+=1
>>> print(a[0])
2
>>> print(b[0])
2
It was a discovery for me. How to make copied array independent?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Klimenko, 2016-01-07
@Fisab

the easiest

a = b[:]
# или
a = b.copy()

but this won't help if the list is part of itself:
b = [1, 2]
>>> b.append(b)
>>> b
[1, 2, [...]]
>>> id(b)
139920848119752
>>> id(b[2])
139920848119752
>>> a = b[:]
>>> a
[1, 2, [1, 2, [...]]]
>>> id(a)
139920848120456
>>> id(a[2])
139920848119752

but deepcopy will already cope with this
from copy import deepcopy
>>> a = deepcopy(b)
>>> a
[1, 2, [...]]
>>> id(a)
139920847744840
>>> id(a[2])
139920847744840

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question