Created
July 14, 2011 13:54
-
-
Save Visgean/1082496 to your computer and use it in GitHub Desktop.
Getting copy of lists or objects in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> a = ["a","b","c"] | |
>>> b = a | |
>>> b.append("d") | |
>>> print a, b | |
['a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd'] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>> class obj: | |
... def __init__(self): | |
... self.counter = 0 | |
... def inc(self): | |
... self.counter += 1 | |
... | |
>>> a = obj() | |
>>> b = a | |
>>> a.inc() | |
>>> print a.counter | |
1 | |
>>> print b.counter | |
1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> a = ["a","b","c"] | |
>>> b = list(a) | |
>>> print a , b | |
['a', 'b', 'c'] ['a', 'b', 'c'] | |
>>> a.append("d") | |
>>> print a, b | |
['a', 'b', 'c', 'd'] ['a', 'b', 'c'] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> class obj: | |
... def __init__(self): | |
... self.counter = 0 | |
... def inc(self): | |
... self.counter += 1 | |
... | |
>>> a = obj() | |
>>> from copy import copy | |
>>> b = copy(a) | |
>>> a.inc() | |
>>> b.inc() | |
>>> b.inc() | |
>>> b.inc() | |
>>> print a.counter, b.counter | |
1 3 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> a = [1,2,3] | |
>>> b = a[:] | |
>>> b.append(3) | |
>>> b | |
[1, 2, 3, 3] | |
>>> a | |
[1, 2, 3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment