Now that you know the difference between mutable and immutable objects, the question arises: When do I need to use mutable and when immuatble objects? This question is covered in the video at hand.
When to Use Immutable vs Mutable Objects
00:10 That seems to be a pretty clear definition. I want to go a little bit deeper into some of the oddities that you might encounter when it comes to immutable objects in Python. But before I do that, let’s talk about when you want to use mutable and when you want to use immutable objects and what they’re good for.
00:28 The great thing about an immutable object is that it is sealed. It can’t really be modified once it’s been created. And that can be a really helpful property if you want to write code that’s easier to debug. Essentially, when you create an immutable object, you will know what its value is going to be, in that its value is going to be constant after it was created.
00:52 So when you’re debugging code that works with immutable objects, it’s much more easy to find out what the current state of an object is. And immutability is also helpful when you’re working with parallelism in your programs, because then you can pretty much guarantee that there won’t be another thread reaching into your data and modifying it when you don’t expect it. Now, it’s extremely hard to write all of your code in a way that makes it completely immutable, at least in Python—and I’m going to show you why in a minute—but the general idea of when you want to apply immutability or want to use immutable objects is when you want to seal objects, you want to guarantee that their value and their contents are not going to change. Now, with mutable objects, you would always use them if you need to modify an object or a container as you go along.
01:43 Right? Let’s say you wrote an algorithm that collects a bunch of names in a list. Then you would obviously have to keep adding these names to the list. I mean, you could implement that algorithm in a way where instead of modifying the list by adding an element, it would actually create a completely new list from scratch and just overwrite the list object, which could be a good thing from a debuggability perspective.
02:10 But generally, that will be a slower approach than updating the list in place. So that’s another trade-off you need to look out for, right? Immutable objects are, I guess you could say, safer and easier to debug, but the downside is it will always be faster to just reach in and modify an object in place.
Become a Member to join the conversation.