Creating Python variables independent of each other

If I have this Python code:

foo = [3, 5, 9]
bar = foo
bar.append(9)
print(foo)

He returns

[3, 5, 9, 9]

This, of course, means that when added 9to barit also affected foo. How to make a variable barequal foo, but so that when I edit barit does not affect foo?

+2
source share
4 answers

You are modifying the mutable value, so you need to make an explicit copy:

bar = list(foo)

or

bar = foo[:]

When assigning a name in Python, all you do is keep a reference to the value. Without creating a copy of the list, both fooand barbelong to the same list.

; , , , .

( dict set ) . foo, foo. foo.append(9), Python :

  • foo .
  • .append . .
  • , 9. .

Python , , . , , - . bar = foo , .

, .

+5

:

bar = foo[:]  #copy of foo
bar.append(9)

, python . " " . , foo bar, , .

, (, +=), . . .

+2

When creating copies of the original while deleting all references to it (so you cannot edit the original), you use a deep copy.

http://docs.python.org/2/library/copy.html

import copy
bar = copy.deepcopy(foo)
+1
source

Use deepcopy:

>>> from copy import deepcopy
>>> foo = [3, 5, 9]
>>> bar = deepcopy(foo)
>>> bar.append(9)
>>> print(foo)
[3, 5, 9]
>>> print bar
[3, 5, 9, 9]
+1
source

Source: https://habr.com/ru/post/1678833/


All Articles