Shallow vs Deep Copying in Python - Advanced Python 20 - Programming Tutorial

Patrick Loeber · Beginner ·🛠️ AI Tools & Apps ·6y ago

Key Takeaways

This video tutorial covers the concept of shallow and deep copying in Python, using the built-in copy module to create copies of mutable elements, including lists and custom objects.

Full Transcript

hi everybody welcome to a new Python tutorial in this tutorial we will talk about copying so we will learn how we can copy mutable elements with a built-in copy module and the difference between shallow and deep copies and we will also have a look at how to make actual copies of custom objects so let's start and first of all let's have a look at the assignment operator so let's say we have a variable call it orc and this is now a number and now if you want to make a copy with an assignment so we say copy equals original then this will not make a real copy it will only create a new variable with the same reference so now both variables point to the same number and now for immutable types like this integer this is not a problem so let's say if we change the copy then say copy equals 6 then this assignment will again create a new variable so days they are now both independent so if we print the copy and if we print the original they are different but when we deal with mutable types so for example a list then we have to be careful so let's say we have a list here with some elements so let's say 0 1 2 3 4 and now we make a copy with this assignment operator and then if we change elements of our copy so let's say we want to change the first item and say this is now minus 10 and now if you print both the copy and the original we see that also the original has the value minus 10 here and this is because this assignment operator doesn't make an actual copy so to make an actual copy we can use the built-in copy module so we can say import copy and then we have to make a difference between shallow and deep being so a shallow copy is only one level deep so at the first level it makes an actual copy but then it only copies references of the nested child objects and then there's the deep copy so this will be in a full independent copy so let's start with an with a shallow copy so to make a shallow copy we can say copy equals copy dot copy and then the original and now if we print both we see that the original didn't get affected so only the copy here has minus ten and for example with a list there are several different options to make shallow copies so we can also say copy equals original dot copy so this will also work or we can use the list function and give it the original as an argument this is also possible or we can use list slicing so we can say org and then the slicing operator so this will simply be from start to end so this will copy all elements and this will also make an actual copy or a shallow copy so this works fine if our element is only one level deep and now let's say we have a nest or nested list so let's say we have a first list here a list inside a list and then a second list here so that's some more elements three so this is our original list and now we make a shallow copy and now we change an object or an item that is at the second level so we say copy at index zero so in this list and then again and index 0 so this element or for another example let's make index 1 here so this is this element and now this we want to set to minus 10 and now let's see what happens so if we run this we see that both the copy and the original now have minus 10 here and this is because a shallow copy is only one level deep so to make an actual copy in all the levels we have to make a deep copy so we can say copy dot deep copy and now if we run this we see that the original didn't get affected so this is the difference between shallow and deep copying and for the built-in types like lists dictionaries or tuples we can use these methods but we can also use it for custom objects so let's say we have a custom class and call it person and now in the in it it gets self of course and then it gets a name and an age and then we say self dot name equals name and self dot H equals H and now let's create two persons person 1 equals person and now it's a name it gets Alex and as an age let's say 27 and now let's make a copy simply by assigning it so let's say person 2 equals person 1 and now if we change person 2 dot H equals 28 and now if you print person 2 dot H and we also print person 1.8 then we see again and both got affected because this is not an actual copy so here we can use copy dot copy and now if we run this we see we have a shallow copy here so the original person didn't get affected but again now if we have a deeper structure so let's say or let's first create or person class and let's say we also have a class company this gets this has an init method so in it self and now this gets two persons it gets a boss and an employee so self top boss equals boss and self dot employee equals employee and now we create two persons so one boss so the boss might be holder and now a second person Joe with a little bit younger and now let's say we want to have a company so we say company equals company with our person one and our person too and now if we want to make a clone of this so if we say company clone equals company well let's right away make a shallow copy so we can say copy dot copy and now if we change some variable here so let's say one boss turns a year older so let's say company clone top boss dot H equals 56 now and now let's print this print company clone dot boss dot age and also print the age of the boss of the original company so let's say company boss age then again we see it got affected because this is only a shallow copy and the H is at the level 2 so this will again only be a copy of the reference here and in order to make this independent we have to say copy dots deep copy and now if you run this we see that the original boss is still 55 so this is the difference between shallow and deep copying I hope you enjoyed this tutorial and see you in the next tutorial where we will learn about context managers in Python

Original Description

In this Python Advanced Tutorial, we will talk about copying. We will learn how we can copy mutable elements with the built-in copy module, and the difference between shallow and deep copies. We will also have a look at how to make actual copies of custom objects. ~~~~~~~~~~~~~~ GREAT PLUGINS FOR YOUR CODE EDITOR ~~~~~~~~~~~~~~ ✅ Write cleaner code with Sourcery: https://sourcery.ai/?utm_source=youtube&utm_campaign=pythonengineer * 📚 Get my FREE NumPy Handbook: https://www.python-engineer.com/numpybook 📓 Notebooks available on Patreon: https://www.patreon.com/patrickloeber ⭐ Join Our Discord : https://discord.gg/FHMg9tKFSN If you enjoyed this video, please subscribe to the channel! A written Tutorial can be found here: https://www.python-engineer.com/courses/advancedpython/20-copy/ You can find me here: Website: https://www.python-engineer.com Twitter: https://twitter.com/patloeber GitHub: https://github.com/patrickloeber #Python ---------------------------------------------------------------------------------------------------------- * This is a sponsored link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you so much for the support! 🙏
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Patrick Loeber · Patrick Loeber · 20 of 60

1 Lists in Python - Advanced Python 01 - Programming Tutorial
Lists in Python - Advanced Python 01 - Programming Tutorial
Patrick Loeber
2 Tuples in Python - Advanced Python 02 - Programming Tutorial
Tuples in Python - Advanced Python 02 - Programming Tutorial
Patrick Loeber
3 Dictionaries in Python - Advanced Python 03 - Programming Tutorial
Dictionaries in Python - Advanced Python 03 - Programming Tutorial
Patrick Loeber
4 Sets in Python - Advanced Python 04 - Programming Tutorial
Sets in Python - Advanced Python 04 - Programming Tutorial
Patrick Loeber
5 Strings in Python - Advanced Python 05 - Programming Tutorial
Strings in Python - Advanced Python 05 - Programming Tutorial
Patrick Loeber
6 Collections in Python - Advanced Python 06 - Programming Tutorial
Collections in Python - Advanced Python 06 - Programming Tutorial
Patrick Loeber
7 Itertools in Python - Advanced Python 07 - Programming Tutorial
Itertools in Python - Advanced Python 07 - Programming Tutorial
Patrick Loeber
8 Lambda in Python - Advanced Python 08 - Programming Tutorial - Map Filter Reduce
Lambda in Python - Advanced Python 08 - Programming Tutorial - Map Filter Reduce
Patrick Loeber
9 Exceptions in Python - Advanced Python 09 - Programming Tutorial
Exceptions in Python - Advanced Python 09 - Programming Tutorial
Patrick Loeber
10 Logging in Python - Advanced Python 10 - Programming Tutorial
Logging in Python - Advanced Python 10 - Programming Tutorial
Patrick Loeber
11 JSON in Python - Advanced Python 11 - Programming Tutorial
JSON in Python - Advanced Python 11 - Programming Tutorial
Patrick Loeber
12 Random Numbers in Python - Advanced Python 12 - Programming Tutorial
Random Numbers in Python - Advanced Python 12 - Programming Tutorial
Patrick Loeber
13 Decorators in Python - Advanced Python 13 - Programming Tutorial
Decorators in Python - Advanced Python 13 - Programming Tutorial
Patrick Loeber
14 Generators in Python - Advanced Python 14 - Programming Tutorial
Generators in Python - Advanced Python 14 - Programming Tutorial
Patrick Loeber
15 Threading vs Multiprocessing in Python - Advanced Python 15 - Programming Tutorial
Threading vs Multiprocessing in Python - Advanced Python 15 - Programming Tutorial
Patrick Loeber
16 Threading in Python - Advanced Python 16 - Programming Tutorial
Threading in Python - Advanced Python 16 - Programming Tutorial
Patrick Loeber
17 Multiprocessing in Python - Advanced Python 17 - Programming Tutorial
Multiprocessing in Python - Advanced Python 17 - Programming Tutorial
Patrick Loeber
18 Function arguments in detail - Advanced Python 18 - Programming Tutorial
Function arguments in detail - Advanced Python 18 - Programming Tutorial
Patrick Loeber
19 The asterisk (*) operator in Python - Advanced Python 19 - Programming Tutorial
The asterisk (*) operator in Python - Advanced Python 19 - Programming Tutorial
Patrick Loeber
Shallow vs Deep Copying in Python - Advanced Python 20 - Programming Tutorial
Shallow vs Deep Copying in Python - Advanced Python 20 - Programming Tutorial
Patrick Loeber
21 Context Managers in Python - Advanced Python 21 - Programming Tutorial
Context Managers in Python - Advanced Python 21 - Programming Tutorial
Patrick Loeber
22 KNN (K Nearest Neighbors) in Python - Machine Learning From Scratch 01 - Python Tutorial
KNN (K Nearest Neighbors) in Python - Machine Learning From Scratch 01 - Python Tutorial
Patrick Loeber
23 Linear Regression in Python - Machine Learning From Scratch 02 - Python Tutorial
Linear Regression in Python - Machine Learning From Scratch 02 - Python Tutorial
Patrick Loeber
24 Logistic Regression in Python - Machine Learning From Scratch 03 - Python Tutorial
Logistic Regression in Python - Machine Learning From Scratch 03 - Python Tutorial
Patrick Loeber
25 Linear and Logistic Regression in 60 lines of Python - Machine Learning From Scratch 04
Linear and Logistic Regression in 60 lines of Python - Machine Learning From Scratch 04
Patrick Loeber
26 Naive Bayes in Python - Machine Learning From Scratch 05 - Python Tutorial
Naive Bayes in Python - Machine Learning From Scratch 05 - Python Tutorial
Patrick Loeber
27 Perceptron in Python - Machine Learning From Scratch 06 - Python Tutorial
Perceptron in Python - Machine Learning From Scratch 06 - Python Tutorial
Patrick Loeber
28 SVM (Support Vector Machine) in Python - Machine Learning From Scratch 07 - Python Tutorial
SVM (Support Vector Machine) in Python - Machine Learning From Scratch 07 - Python Tutorial
Patrick Loeber
29 Decision Tree in Python Part 1/2 - Machine Learning From Scratch 08 - Python Tutorial
Decision Tree in Python Part 1/2 - Machine Learning From Scratch 08 - Python Tutorial
Patrick Loeber
30 Decision Tree in Python Part 2/2 - Machine Learning From Scratch 09 - Python Tutorial
Decision Tree in Python Part 2/2 - Machine Learning From Scratch 09 - Python Tutorial
Patrick Loeber
31 Random Forest in Python - Machine Learning From Scratch 10 - Python Tutorial
Random Forest in Python - Machine Learning From Scratch 10 - Python Tutorial
Patrick Loeber
32 PCA (Principal Component Analysis) in Python - Machine Learning From Scratch 11 - Python Tutorial
PCA (Principal Component Analysis) in Python - Machine Learning From Scratch 11 - Python Tutorial
Patrick Loeber
33 K-Means Clustering in Python - Machine Learning From Scratch 12 - Python Tutorial
K-Means Clustering in Python - Machine Learning From Scratch 12 - Python Tutorial
Patrick Loeber
34 Anaconda Tutorial - Installation and Basic Commands
Anaconda Tutorial - Installation and Basic Commands
Patrick Loeber
35 PyTorch Tutorial 01 - Installation
PyTorch Tutorial 01 - Installation
Patrick Loeber
36 PyTorch Tutorial 02 - Tensor Basics
PyTorch Tutorial 02 - Tensor Basics
Patrick Loeber
37 PyTorch Tutorial 03 - Gradient Calculation With Autograd
PyTorch Tutorial 03 - Gradient Calculation With Autograd
Patrick Loeber
38 PyTorch Tutorial 04 - Backpropagation - Theory With Example
PyTorch Tutorial 04 - Backpropagation - Theory With Example
Patrick Loeber
39 PyTorch Tutorial 05 - Gradient Descent with Autograd and Backpropagation
PyTorch Tutorial 05 - Gradient Descent with Autograd and Backpropagation
Patrick Loeber
40 PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer
PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer
Patrick Loeber
41 PyTorch Tutorial 07 - Linear Regression
PyTorch Tutorial 07 - Linear Regression
Patrick Loeber
42 PyTorch Tutorial 08 - Logistic Regression
PyTorch Tutorial 08 - Logistic Regression
Patrick Loeber
43 PyTorch Tutorial 09 - Dataset and DataLoader - Batch Training
PyTorch Tutorial 09 - Dataset and DataLoader - Batch Training
Patrick Loeber
44 PyTorch Tutorial 10 - Dataset Transforms
PyTorch Tutorial 10 - Dataset Transforms
Patrick Loeber
45 Download Images With Python Automatically - Python Web Scraping Tutorial
Download Images With Python Automatically - Python Web Scraping Tutorial
Patrick Loeber
46 PyTorch Tutorial 11 - Softmax and Cross Entropy
PyTorch Tutorial 11 - Softmax and Cross Entropy
Patrick Loeber
47 Select Movies with Python - Web Scraping Tutorial
Select Movies with Python - Web Scraping Tutorial
Patrick Loeber
48 PyTorch Tutorial 12 - Activation Functions
PyTorch Tutorial 12 - Activation Functions
Patrick Loeber
49 List Comprehension in Python - A Python Feature You MUST KNOW - Python Tutorial
List Comprehension in Python - A Python Feature You MUST KNOW - Python Tutorial
Patrick Loeber
50 PyTorch Tutorial 13 - Feed-Forward Neural Network
PyTorch Tutorial 13 - Feed-Forward Neural Network
Patrick Loeber
51 How To Add A Progress Bar In Python With Just One Line - Python Tutorial
How To Add A Progress Bar In Python With Just One Line - Python Tutorial
Patrick Loeber
52 PyTorch Tutorial 14 - Convolutional Neural Network (CNN)
PyTorch Tutorial 14 - Convolutional Neural Network (CNN)
Patrick Loeber
53 The Walrus Operator - New in Python 3.8 - Python Tutorial
The Walrus Operator - New in Python 3.8 - Python Tutorial
Patrick Loeber
54 PyTorch Tutorial 15 - Transfer Learning
PyTorch Tutorial 15 - Transfer Learning
Patrick Loeber
55 YouTube Data API Tutorial with Python - Analyze Channel Statistics - Part 1
YouTube Data API Tutorial with Python - Analyze Channel Statistics - Part 1
Patrick Loeber
56 YouTube Data API Tutorial with Python - Find Channel Videos - Part 2
YouTube Data API Tutorial with Python - Find Channel Videos - Part 2
Patrick Loeber
57 YouTube Data API Tutorial with Python - Get Video Statistics - Part 3
YouTube Data API Tutorial with Python - Get Video Statistics - Part 3
Patrick Loeber
58 YouTube Data API Tutorial with Python - Analyze the Data - Part 4
YouTube Data API Tutorial with Python - Analyze the Data - Part 4
Patrick Loeber
59 AdaBoost in Python - Machine Learning From Scratch 13 - Python Tutorial
AdaBoost in Python - Machine Learning From Scratch 13 - Python Tutorial
Patrick Loeber
60 Ultimate FREE Study Guide for Machine Learning and Deep Learning
Ultimate FREE Study Guide for Machine Learning and Deep Learning
Patrick Loeber

This tutorial teaches how to create copies of mutable elements in Python, including lists and custom objects, using the built-in copy module. It covers the difference between shallow and deep copying and how to use these concepts in practice.

Key Takeaways
  1. Import the copy module
  2. Create a shallow copy of a list using copy.copy()
  3. Create a deep copy of a list using copy.deepcopy()
  4. Create a shallow copy of a custom object using copy.copy()
  5. Create a deep copy of a custom object using copy.deepcopy()
💡 Shallow copying only copies the references of nested child objects, while deep copying creates a fully independent copy of all levels.

Related AI Lessons

Up next
I Asked ChatGPT to Apply to 500 Jobs (8 Interviews in 48 Hours)
Sabrina Ramonov 🍄
Watch →