Complex Data Types in Python: Shallow & Deep Copies in Python
Learn about copying operations on containers in Python. You will learn the subtle distinction between shallow and deep copies. Changes made to shallow copies affect the original whereas with deep copies do not.
Table of Contents
- Course Overview
- Copying Strings
- Performing Shallow Copies of Lists
- Performing Deep Copies of Lists
- Creating Shallow and Deep Copies of Tuples
- Creating Shallow Copies of Dictionaries
- Creating Deep Copies of Dictionaries
- Creating Shallow and Deep Copies of Sets
- Exercise: Shallow and Deep Copies
Shallow and Deep Copies
- A shallow copy are made when two variables with different variable names point to the same location in memory.
- Updates that you make using one variable are reflected when accessing the same data using the other variable.
- The same complex data type has just two names with shallow copies.
- Deep copies are made when the same data is copied over to an entirely new memory location.
- Changes made to the deep copy are not reflected in the original memory.
- Once created, strings cannot be updated
- Using assignment operations with strings reference the same location in memory
- But that location cannot be changed
- Assigning a new string value to a variable just creates a new string
list_b=list_a (Shallow Copy)
list_b=list_a[:] (Deep Copy)
list_b=copy.copy(list_a) (Deep Copy of the outer list but shallow copies of nay complex data types)
list_b=copy.deepcopy(list_a) (Deep Copy of the outer list and all of the nested data types)
- Updates that you make using one variable are reflected when accessing the same data using the other variable.
- The same complex data type has just two names with shallow copies.
- Deep copies are made when the same data is copied over to an entirely new memory location.
- Changes made to the deep copy are not reflected in the original memory.
String Copy
- String are immutable in Python- Once created, strings cannot be updated
- Using assignment operations with strings reference the same location in memory
- But that location cannot be changed
- Assigning a new string value to a variable just creates a new string
list_b=list_a (Shallow Copy)
list_b=list_a[:] (Deep Copy)
list_b=copy.copy(list_a) (Deep Copy of the outer list but shallow copies of nay complex data types)
list_b=copy.deepcopy(list_a) (Deep Copy of the outer list and all of the nested data types)
No comments:
Post a Comment