Python: Copy Nested List, Shallow/Deep Copy
What is Shallow Copy?
- Shallow Copy of a nested list is such that for each nested list in it, the reference of the list is copied, not the list's content. When a reference of a list is copied, changing items in copied version also changes the original version, and vice versa.
- Deep Copy of a nested list is copying the actual items in any nested list. (the result copy is not connected with the original version.)
All the following do shallow copy:
listB = listA.slice(…)
listB = listA.extend(…)
listB = list(listA)
# example of shallow copy. Changing a nested item changes the original xx = [[1, 2], 3] yy = list(xx) # modify xx xx[0][1] = 9 # all true print(xx == [[1, 9], 3]) print(yy == [[1, 9], 3]) print(xx == yy)
See also: Python: dictionary.clear vs Set Dictionary to Empty .
Copying Nested List, Deep Copy
Use the module “copy” to make a truely independent copy of a list.
import copy xx = [[3, 4], 5] yy = copy.deepcopy(xx) xx[0][0] = 9 print(xx == [[9, 4], 5]) print(yy == [[3, 4], 5])
Copying List by Reference (Shallow Copy)
If you do this listA = listB
, that'll copy a reference. That means: modifying one list also modifies the other.
xx = [3, 4, 5] yy = xx xx[0] = 7 print(yy == [7, 4, 5])
Check Equality of 2 Objects
You can check by using the “id” function. The id(obj)
returns the object's memory address.
aa = [3, 4, 5] bb = aa print(id(aa)) # 4477411144 print(id(aa) == id(bb)) # True
Copy Flat List Using List Slice
You can make a copy by listB = listA[:]
. When the first index are omitted, it default to 0. When the ending index is omitted, it default to length of the list.
xx = [3, 4, 5] yy = xx[:] print((id(xx) == id(yy)) == False) print(xx == yy) # all True
Copy Flat List Using .extend()
xx = [3, 4, 5] yy = [] yy.extend(xx) print((id(xx) == id(yy)) == False) print(xx == yy) # all True
Copy Flat List Using list()
The best way to copy flat list is
listB = list(listA)
xx = [3, 4, 5] yy = list(xx) print((id(xx) == id(yy)) == False) print(xx == yy) # all True
Python, Data Structure
- Python: List
- Python: Generate List: range
- Python: List Comprehension
- Python: List Methods
- Python: Iterate List
- Python: Map f to List
- Python: Filter List
- Python: Iterator to List
- Python: Copy Nested List, Shallow/Deep Copy
- Python: Interweave Lists to Tuples, Transpose
- Python: Sort
- Python: Convert List to Dictionary
- Python: Dictionary
- Python: Iterate Dictionary
- Python: Dictionary Methods
- Python: Tuple
- Python: Sets, Union, Intersection
- Python: Sequence Types
- Python: Read Write JSON