Copying Techniques
1. Reference Copy Method
original_list = [1, 2, 3, 4]
reference_list = original_list
reference_list[0] = 99
print(original_list) ## Both lists change
2. Shallow Copy Techniques
Using Slice Method
original_list = [1, 2, 3, 4]
shallow_copy = original_list[:]
Using list() Constructor
shallow_copy = list(original_list)
Using copy() Method
shallow_copy = original_list.copy()
3. Deep Copy Method
import copy
original_list = [1, 2, [3, 4]]
deep_copy = copy.deepcopy(original_list)
Comparison of Copying Techniques
| Technique |
Method |
Nested Objects |
Performance |
| Reference |
= |
Shared |
Fastest |
| Shallow Copy |
[:], list(), .copy() |
Referenced |
Fast |
| Deep Copy |
copy.deepcopy() |
Fully Copied |
Slowest |
flowchart TD
A[Original List] --> B{Copying Method}
B --> |Reference| C[Same Memory Reference]
B --> |Shallow Copy| D[New List, Shared Nested Objects]
B --> |Deep Copy| E[Completely Independent List]
Practical Considerations
- Use shallow copy for simple, non-nested lists
- Use deep copy when dealing with nested structures
- Consider performance implications for large lists
LabEx recommends understanding these techniques to write efficient Python code.