Skip to content

Instantly share code, notes, and snippets.

@Visgean
Created July 14, 2011 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Visgean/1082496 to your computer and use it in GitHub Desktop.
Save Visgean/1082496 to your computer and use it in GitHub Desktop.
Getting copy of lists or objects in python
>>> a = ["a","b","c"]
>>> b = a
>>> b.append("d")
>>> print a, b
['a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd']
>> 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
>>> 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']
>>> 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
>>> 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