Mutable vs Immutable - Python
Key Takeaways
The video explains the concept of mutable and immutable objects in Python, including lists, sets, dictionaries, integers, floats, strings, and tuples, and how they behave differently in memory.
Full Transcript
hey guys and welcome back to another video in today's video I'm going to be explaining the difference between mutable and immutable data types this is an extremely extremely important concept it's fundamental to any programming you're gonna do in Python this is completely different from most other languages so even if you think you're a good programmer or maybe you program in Java and C and you're here to learn some Python make sure you watch the entire video and understand this because this is not something you would have learned before in other languages this is what makes Python distinct difference obviously a lot of other factors as well but this is completely different from other programming languages and it can cause a huge headache if you don't understand it so make sure if you do not understand that you watch through the entire video because I'm gonna be explaining it in depth and it is really a fundamental concept I can't emphasize that enough when I started programming I really wish at least with Python that I learned this right away as it would have saved me a lot of time and made my life a lot easier anyways let's go through so what is a mutable data type and what is an immutable data type well mutable let's type it out here for you so it's supposed to be a comment I don't know how I ended up hitting that okay mutable stands for changeable and immutable stands for not changeable so our mutable data types in Python are lists we have a set and we have a dictionary there's a few other ones but these are the standard built-in data types that are mutable in Python our immutable data types are everything else so everything else would contain like int strings I don't know what else do we have here floats tuples and so on there's obviously a lot of other data types I won't type them all out okay so let's just see an example here difference like how does this work what's what's the difference so pretty much I'm just going to create X I'm gonna make this equal to string I'm in space a Y it's gonna be a new list gonna have one and two in it like that now I will just type that out for here so the type of X obviously is a string and are the type of Y is a list so you can see that our list falls within mutable data types and our string falls within immutable data type so let's see what the main difference here is so I'm gonna show you we can do so with a list I hope you know you can do stuff like dot append so I and say why not append what's a pen two three to it if I print Y then Y is now equal to one two three I can do things like y1 equals seven print y you can see we get one seven three now notice I didn't have to say y equals y1 or I'd have to say y equals and then print the list again like one seven three something like that all I had to do was just say y1 equals I and like dot append simply okay so with our string now let's see if we can do the same thing so I'm gonna say X plus s and you can see that it gives us strings like this so now let's see if I print X well it's still equal to string by doing this plus s here this returned to us a new string with a added s to it whereas it doesn't actually change the value so if I do something like y1 equals seven it doesn't return to us we don't get anything printed after neath it underneath it sorry it doesn't return to us a new list with the changed values like one seven two it simply changes this original list now let's do some examples of alias and cloning and I'll talk about what that is alias just means another name for and cloning means like to copy okay so an alias of a list and this is works for all mutable data types like lists set dictionaries is if I do something like this so so LST equals y and I can print Y and I can print LST and we can see they are indeed the same now I'm just gonna close this and open up because I don't like working out the bottom of my screen okay so actually I'm gonna do this again so I was gonna say list equals one two three let's say x equals LST right so I print X and I put an LST you can see they are indeed the same so now let's see what happens if I change X I'm gonna say X dot append eight likes that so now we should have a list says one two three eight so I print X and I get one two three eight now list I didn't do I didn't do anything to list I didn't change list so it should just be equal to 1/2 right so let's see if I print list but it's not it's equal to one two three eight now why did that happen well when we assigned the value of LST to X we simply created an alias for this list meaning that we just created another name for it it really that completely this line is completely useless it doesn't really change anything in memory and I'm gonna show this later with like a little drawing example to make it more clear we've simply just said okay X is equal to this list so whatever we do to this list is gonna change X as well whenever we do two X is given change this list as well they simply are the exact same object so any operation we do on that is going to apply to both of them because we created an alias by simply just doing this like assignment like this and you can have as many alias as you want so I can say y equals LST front Y I'm gonna do y dot append oops I've got 100 I print X Y and LST and you can see they're all equal to the same thing like that now let's watch it would have how this works with strings so immutable data types not mutable data types so I say x equals oops equals STR and I say X or if let's say y equals x I can print X I can print Y you can see we get STR STR and now if I do X plus equals like five I'll print X and I get string five now if I print Y we just get string so the operation that I applied to Y did not actually change X it did not change that value that's because these types are immutable meaning that you can't change them same thing with numbers right so if you do like x equals 5 y equals 6 like this or hot one my second let's say y equals x like that and then you do like x equals x plus 5 and you change it and then you print Y well why didn't change it's still equal to 5 whereas X is equal to 10 and that is the main difference between mutable and immutable data types one you can change one you can no now I want to get into a memory model for these that's gonna explain it a lot more clear so have like a little drawing tablet thing that I got recently excuse me my handwriting is absolutely atrocious so there's really gonna be some symbols or letters you might not feel to make out but just bear with me this is one of the easiest ways that I can kind of explain it to you guys so I'm just gonna do this screen sketch all right so now it brings up this thing so let's make sure this is working all right okay so she's gonna go to pen here and I'm just gonna draw like a standard thing that I want to call the memory model and Python this is what is actually happening in your computer when you create lists and you create like integers and all that kind of stuff so we created a list here LST is equal to 1 2 3 so what this is done now is it's pointed LST points to a list in our memory that looks like this 1 2 3 ok so it points to that list in memory and it actually doesn't quite point to that list but I'll talk about that after this is just the easiest way to explain ok and X now so X is equal to list what this actually does is it points to these same lists right so it makes sense they point to the same list now I'll show you down here when I created a string and when I said y equals x so when I create the string X what happens is we come up here and we have a string and it's equal to like s T are like that and that's gonna be X and I'm just gonna put X LST sir I should use different names for these but you can see so that's the value of x n LST this value X now when I say y equals x well what actually ends up happening is I come here and I point to a new string that's equal to s TR like that again sorry but the awful handwriting but you get the point so rather than these immutable objects pointing to the same object we point to two different instances of strings so that's why when I add a 5 here so like say out of 5 so let's just erase this it doesn't actually change our other value because well this is its own object so when we print that out you can see that it doesn't have the 5 attached to 1 whereas up here if we change for example this value - and we change this to seven well that changes X as well because X is pointing to this same object and I hope that makes sense and this word this is the same kind of situation for mutable and immutable and immutable data types so if we want to create a copy something I'll show you how we can do that after but I hope this guides this gave you like an explanation of why that works so the same thing with integers if I created like let's say like x equals or whatever I'm using ax writing is x equals 6 then we get 6 here and I say y equals x then we get another 6 here and you can see that we point like that and we point like that ok so we get six six two different sixes we're not pointing to the same object whereas with this list that is precisely what's happening ok so I made a bit of a mess here so let's just go ahead and close this out and go back to typing some that stuff out here so what I'm gonna do now is I'm going to bring in like I have another file that I was writing here and just show you some examples of how we can kind of use this property so I have like a little summary of kind of what gone on went on here so mutable types you made will data types oh and of course I've closed that just give me a second guys what's gonna reopen this ok so I've got the file back up sorry about that anyways we have a change list and copy list these are two functions and then we have some operators down here so you can see here what's gonna happen so I'm just gonna actually call these functions down here to kind of illustrate what happens so this first function change list simply appends a hundred to a given list you can see it doesn't return anything all it does is it says l I don't append a hundred okay so what we have to do is we're gonna pass a list so I'm gonna say change list and we'll just do like one two three are actually I have to do like this otherwise we're not gonna be able to track what we're doing so X I give it X and then if I print X down here and I'm just gonna comment out all this so that we don't get that printing instead what happens here is I'm gonna print X so you can see if I do this I get one two three one hundred so again this is the same thing that I was talking about before when we say with the parameter the way parameters work in functions is whatever the past value is becomes equal to this name so Li is this is doing exactly this Li is equal to X that's simply all that it's executing Li equals x so when we pass X in here so okay Li is equal to X well that's one two three and they're the same object so when we change something on Li we're effectively changing X as well now I want to show you what happens when I do copy list so this copy list I haven't talked about what this does yet but I'll do it in just a second I change this to copy list and print X okay so actually I'm going to say I have to say X is equal to copy list year okay so what this copy list does is it creates a copy of the given list so we say x equals to L I here again now we're saying new list is equal to Li square bracket colon square bracket now what this does is it makes a copy so a new object of our list it's not this it's not no longer now pointing to the same object and they're pointing to a different object in memory that are just like identical okay so I hope that makes sense I'm going to explain this more with another like drawing thing after and then we're appending a hundred to that new list and we're returning that new list so let's now run the operation here so X use one two three copy list print X see we get one two three hundred but if I say oops let's just do Y here imprint XY otherwise we're not going to see so X is the original list Y is the change list you can see that we have one two three which was our original list that we passed in and then our new list one two three hundred and notice that hundred is not added to the old list because we simply copied it we did not actually change that original list okay so now I'm gonna talk about this is operator and what this does is it allows us to check whether two items are the same within memory so what I was telling you before was somewhat a lie somewhat true I was telling you that when you create a variable say like x equals one two three it points to a location in memory where we have one two three just a list one two three and not that's it that's not completely true what happens is actually each of these objects have an ID associated with them you see I'm printing ID like this and the ID is like the actual specific location in memory so I'm just gonna get out my tablet and start drawing in okay so I've got everything set up pretty well now and what I want to do is I'm gonna redraw that memory model that I was talking about before except we're gonna change a few things so we're gonna go to this LST here and remember I'm always saying that everything is actually in ID it's not actually the value so this is the value right here like 1 2 3 right but what's actually gonna be stored in this memory model when we create list is in address now this address is known as an ID like what I have done here so the ID will look something not really but it's gonna be like a big string of numbers so I'm just gonna say 0 1 okay now this is an ID this is obviously not the value 1 2 3 now this ID points to a value so we change colors here so that we don't get too confused this is 0 1 points to a value that's gonna be this list and once we go start going further than this it kind of gets a little complicated but we have 1 2 3 like this and this ID points to that value so when I create an alias so like what I've done here let's change back to red what happens is this LST here is given the same ID so these lists so LST points to 0 1 and LST 2 also points to 0 1 now once we have 0 1 0 1 points to 1 2 3 which is that value and that is known as the ID and that's what you can get by doing this little function here that I'm going to talk about ID and then whatever item or object whatever variable name okay so what this is operator does and I'm gonna demonstrate this with code is it checks to see if these two IDs are the same so rather than doing something and I guess I'll write down here by doing like 1 equal equal to 1 which is comparing that the values are the same we're checking if the d is the same so if I say one okay let's I need to uh let's actually just erase that and do like a better example here to kind of show you how this operator works so what I'm gonna do is I'm going to create X or make that equal to one say like a thousand I'm gonna say Y is equal to a thousand now if I were to do something like x equals equals y well that gives us true right because they are the same value but if I did we just say X is y that's actually false now you'd say well what like a thousand is a thousand but the thing is remember what I was saying that we're pointing to different objects when we create the variable so when I create x equals a thousand what ends up happening is we come up here we get an ID that looks like 0 2 okay and this ID now points straw another black line here to a thousand like that okay so boom we're pointing to a thousand all right now when I create Y well same thing that I showed before Y comes up here and it's now actually created to an ID that's 0 3 and 0 3 simply points to the value a thousand like that ok now I know we're gonna be confusing here but try to follow along so when I say is X equal to Y well we go to the ID we say okay so 0 2 that's a thousand 0 3 that's a thousand these are the same boom correct they are equal to when I say X is y where we go just to the IDs we don't care about the value when we say is we just care about the IDs and say well this ID is 0-2 this one here that I'm underlining and this one here is 0 3 now are those the same well no they're not so obviously this is gonna return false now when we do something like lists okay so I have LST and LST 2 so just go say LST is LST - like that well what do you think that's gonna return well LST has an ID of 0 1 and LST 2 also has an ID of 0 1 so that gives us a true value like that now when you create a copy and I guess I'll just show this I'm gonna clear the screen here just cuz I have a big mess I create another like standard memory okay when I create a copy so I say LS t so L s T and then that points over here to we have again our list which looks like zero one two or what am I having one two three K you know what just pretend us has one two three I don't feel like writing it again and then I say LS T 2 equals L is T those point to the same thing but when I say LS t 3 equals LS t and then we have this little colon thing here and I'm just skipping the IDs just to show you here what ends up happening is you say LS T 2 points to and then we actually create a new list so again a new ID and we get well 0 1 & 2 like that so these are no longer pointing to the same object or ID so you can imagine this as like id-1 id2 but simply these IDs are unique and they point to the same object like that i hope that makes sense in terms of like when you make a copy you get a new ID with the identical value of whatever you're copying so a new ID for this list like that okay so that's all I'm going to be doing with the drawing I know you guys are probably tired of seeing my horrible handwriting so let's go back to coding where I can't make hey look at that bad ok so now we're back onto the keyword so what I'm gonna do here is I'm just gonna simply print out some of the stuff that you're talking about so I don't need all these functions up here anymore and let's just see so LS t equals 1 2 3 LS t equals or LS t 2 equals LS t so remember I was saying this should print true and then we create a copy of LS t and I say well as LS t is it equal to that no it should return false so let me just prove this to you run so we get true false and then we get the IDs and this is what I want to talk about with the IDs now that we have these open so we have this one what I was talking about before right since this is simply an alias I want this to stay open of the other list we get true because yes they are actually the same list when using this is operator and then LS t3 well that's not an alias of LS to you that's a copy so they don't have the same ID that's false and then I simply just print out the IDs for you to show you exactly what they look like so LS t well that has an ID four nine four three eight three nine two you can see that this indeed is the same ID for Alice - and LST 3 has a unique ID with different numbers and I'll just show you if I do something like I don't know i D like to 5/9 like that we get that's the number who say like ID of I don't know let's do something like this like STR we had a different number if I create X equals 90 for our 95 and iidx we get another note right so these IDs are unique and they for what do you call it immutable objects at least but if I create Wow let's do another example LS t equals 1 - you say x equals LST ID of X ID of oops LS t we can see that indeed they are the same just one more last proof for any of you that might have been skeptical at there ok so that has been it for explaining immutable and mutable data types I know this was a lot of information and don't feel bad if you're slightly confused but you should hopefully now have an understanding of how kind of the basic memory model in Python works if you have any other questions just let me know [Music]
Original Description
In this video I go over a very detailed explanation of mutable and immutable objects in python. This is an extremely important concept and is is vital that you understand it if you program with python. Mutable objects are changeable and act differently in memory than other objects. You can create copies and aliases of them. Immutable objects are standard data types that cannot be changed or aliased.
Mutable Objects:
- dict
- list
- set
Immutable Objects:
- int
- str
- float
- bool
etc..
Want To Support This Channel?
Bitcoin: 1PbkAYLFaJBgjbKn2ptGyBz65xWN8hJgBU
Ethereum: 0xdd42dbbdba60f7163fc7a840e189474b6e8bfcad
Ripple: rD4arM9CVjQWqi8f1kxdpCgkCgEkqBgtud
Please leave a LIKE and SUBSCRIBE for more content!
Tags:
- Tech
- Tech With Tim
- Python Tutorials
- Mutable Objects
- Immutable objects
- Mutable vs Imuttable python
- Python mutable
- Python immutable
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Tech With Tim · Tech With Tim · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
A* Path Finding Algorithm(Visualization)
Tech With Tim
Python Programming Tutorial #1 - Variables and Data Types
Tech With Tim
Python Programming Tutorial #2 - Basic Operators and Input
Tech With Tim
Python Programming Tutorial #3 - Conditions
Tech With Tim
Python Programming Tutorial #4 - IF/ELIF/ELSE
Tech With Tim
Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Tech With Tim
Python Programming Tutorial #6 - For Loops
Tech With Tim
Python Programming Tutorial #7 - While Loops
Tech With Tim
Python Programming Tutorial #8 - Lists and Tuples
Tech With Tim
Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Tech With Tim
Python Programming Tutorial #10 - String Methods
Tech With Tim
How to Overclock a NVIDIA GPU
Tech With Tim
Python Programming Tutorial #11 - Slice Operator
Tech With Tim
Python Programming Tutorial #12 - Functions
Tech With Tim
Python Programming Tutorial #13 - How to Read a Text File
Tech With Tim
Python Programming Tutorial #14 - Writing to a Text File
Tech With Tim
Python Programming Tutorial #15 - Using .count() and .find()
Tech With Tim
Python Programming Tutorial #16 - Introduction to Modular Programming
Tech With Tim
Python Programming Tutorial #17 - Optional Parameters
Tech With Tim
Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Tech With Tim
Python Programming Tutorial #19 - Global vs Local Variables
Tech With Tim
Python Programming Tutorial #20 - Classes and Objects
Tech With Tim
Cool VBS Script to Prank Your Friends!
Tech With Tim
How to Overclock an AMD GPU
Tech With Tim
Best GPU'S For Mining Ethereum (2018)
Tech With Tim
Recursion and Memoization Tutorial Python
Tech With Tim
Ethereum Mining Rig - Hardware Guide
Tech With Tim
Pygame Tutorial #1 - Basic Movement and Key Presses
Tech With Tim
How to Install Pygame (Windows 8/10)
Tech With Tim
How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
Tech With Tim
How to Mine Ethereum 2018 - WORKING (Super-Easy)
Tech With Tim
Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Tech With Tim
Pygame Tutorial #2 - Jumping and Boundaries
Tech With Tim
Pygame Tutorial #3 - Character Animation & Sprites
Tech With Tim
Pygame Tutorial #4 - Optimization & OOP
Tech With Tim
OBS Studio Tutorial - Best OBS Settings
Tech With Tim
Linear Search Algorithm - Python Example and Code
Tech With Tim
Make Any Mic Sound AMAZING! (WITH OBS)
Tech With Tim
Binary Search Algorithm - Python Example & Code
Tech With Tim
Pygame Tutorial #5 - Projectiles
Tech With Tim
Pygame Game - Mini Golf
Tech With Tim
Pygame Tutorial - Projectile Motion (Part 1)
Tech With Tim
Pygame Tutorial - Projectile Motion (Part 2)
Tech With Tim
Pygame Tutorial #6 - Enemies
Tech With Tim
Pygame Tutorial #7 - Collision and Hit Boxes
Tech With Tim
Pygame Tutorial #8 - Scoring and Health Bars
Tech With Tim
Cloud Mining vs. Hardware Mining - 2018
Tech With Tim
How to Install Pygame on Mac OSX (Fast-Simple)
Tech With Tim
Pygame Tutorial #9 - Sound Effects, Music & More Collision
Tech With Tim
Pygame Tutorial #10 - Finishing Touches & Next Steps
Tech With Tim
How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
Tech With Tim
How to Create a Button in Pygame [CODE IN DESCRIPTION]
Tech With Tim
Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Tech With Tim
Pygame Side-Scroller Tutorial #2 - Random Object Generation
Tech With Tim
Pygame Side-Scroller Tutorial #3 - Collision
Tech With Tim
Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Tech With Tim
How to Create A Message Box in Python - Tkinter
Tech With Tim
Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Tech With Tim
How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
Tech With Tim
Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Tech With Tim
More on: LLM Foundations
View skill →
🎓
Tutor Explanation
DeepCamp AI