Wednesday, February 5, 2020

Complex Data Types in Python: Shallow & Deep Copies in Python

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

  1. Course Overview
  2. Copying Strings
  3. Performing Shallow Copies of Lists
  4. Performing Deep Copies of Lists
  5. Creating Shallow and Deep Copies of Tuples
  6. Creating Shallow Copies of Dictionaries
  7. Creating Deep Copies of Dictionaries
  8. Creating Shallow and Deep Copies of Sets
  9. 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.

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)