Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- newList = oldList[:]
- newList = oldList
- # ================================================================
- # === ShallowCopy.py =============================================
- # ================================================================
- #
- class Foo:
- def __init__(self, data):
- self._data = data
- aa = Foo ('aaa')
- bb = Foo ('bbb')
- # The initial list has two elements containing 'aaa' and 'bbb'
- OldList = [aa,bb]
- print OldList[0]._data
- # The shallow copy makes a new list pointing to the old elements
- NewList = OldList[:]
- print NewList[0]._data
- # Updating one of the elements through the new list sees the
- # change reflected when you access that element through the
- # old list.
- NewList[0]._data = 'xxx'
- print OldList[0]._data
- # Updating the new list to point to something new is not reflected
- # in the old list.
- NewList[0] = Foo ('ccc')
- print NewList[0]._data
- print OldList[0]._data
- >>> # ================================================================
- ... # === ShallowCopy.py =============================================
- ... # ================================================================
- ... #
- ... class Foo:
- ... def __init__(self, data):
- ... self._data = data
- ...
- >>> aa = Foo ('aaa')
- >>> bb = Foo ('bbb')
- >>>
- >>> # The initial list has two elements containing 'aaa' and 'bbb'
- ... OldList = [aa,bb]
- >>> print OldList[0]._data
- aaa
- >>>
- >>> # The shallow copy makes a new list pointing to the old elements
- ... NewList = OldList[:]
- >>> print NewList[0]._data
- aaa
- >>>
- >>> # Updating one of the elements through the new list sees the
- ... # change reflected when you access that element through the
- ... # old list.
- ... NewList[0]._data = 'xxx'
- >>> print OldList[0]._data
- xxx
- >>>
- >>> # Updating the new list to point to something new is not reflected
- ... # in the old list.
- ... NewList[0] = Foo ('ccc')
- >>> print NewList[0]._data
- ccc
- >>> print OldList[0]._data
- xxx
- >>> a = [1, 2, 3, 4]
- >>> b = a
- >>> c = a[:]
- >>> b[2] = 10
- >>> c[3] = 20
- >>> a
- [1, 2, 10, 4]
- >>> b
- [1, 2, 10, 4]
- >>> c
- [1, 2, 3, 20]
- def myfunction(mylist=[]):
- pass
- a = ['one','two','three']
- b = a[:]
- b[1] = 2
- print id(a), a #Output: 1077248300 ['one', 'two', 'three']
- print id(b), b #Output: 1077248908 ['one', 2, 'three']
- a = ['one','two','three']
- b = a
- b[1] = 2
- print id(a), a #Output: 1077248300 ['one', 2, 'three']
- print id(b), b #Output: 1077248300 ['one', 2, 'three']
Add Comment
Please, Sign In to add comment