Immutable vs Mutable Objects in Python

Real Python · Beginner ·🛠️ AI Tools & Apps ·9y ago
https://dbader.org/python-tricks ► Improve your Python skills, one bite at a time and write Pythonic and beautiful code. In Python, immutable vs mutable data types and objects types can cause some confusion—and weird bugs. With this video you'll see what the difference between mutable and immutable data types is in Python, and how you can use it to your advantage in your own programs. You'll also see how to deal with a language quirk in Python that allows objects referenced by immutable types to me modified. Python's definition of "immutable" can be a bit misleading: Basically, the promise of "immutability" on tuples is only partly true. The tuple itself cannot be modified, but objects referenced by the tuple can be. This is sometimes called "non-transitive immutability." If the tuple has an immutable field like a string for example, then it cannot be modified. A mutable field like a list however, can be edited, even if it's embedded in the "immutable" tuple. When the Python documentation refers to an object as being "immutable" they mean the behavior above observed. Other immutable types in Python behave the same way, e.g. namedtuples or frozensets. If you've ever encountered the following exception and now you want to know why, this is the video for you: TypeError: 'tuple' object does not support item assignment * * * ► Python MUGS, T-SHIRTS & MORE: https://nerdlettering.com FREE Python Tutorials & News: » Python Tutorials: https://dbader.org » Python News on Twitter: https://twitter.com/@dbader_org » Weekly Tips for Pythonistas: https://dbader.org/newsletter » Subscribe to this channel: https://dbader.org/youtube

What You'll Learn

The video explains the difference between immutable and mutable objects in Python, providing examples and code demonstrations to illustrate the concepts of immutability and mutability, and how they can impact debugging and parallelism in Python programming.

Full Transcript

hey there this is Dan and in this video I want to talk about immutability in Python so in this video I want to show you what immutability means what does it mean when an object is immutable or we refer to an object as immutable and then I want to talk about the specifics of immutability in Python because there are actually some aspects of it that are not that intuitive especially if you're coming from a different language background and um I want to cover those so that you know what's going on in and you know how to handle these situations when you encounter them in practice all right so let's get started so to demonstrate what immutable or immutability means I'm going to create a mutable object and then an immutable object and then I'm going to show you the difference so for a mutable object which means an object that can be freely modified um an example would be to create a simple list so I'm going to create a list and I'm going to put some values into it or actually let's go with a b and c and with a mutable object I can freely modify this object so I can go in here and I can say let's change let's change the value at index one and when we look at mutable object you can see here that this mutation was applied so we modified the contents of this object Now with an immutable object we can't do that and example for an immutable object would be a tuple here so I'm going to create a tuple with the same contents and now when we try to apply the same modification we're getting a type error Tuple object does not support item assignment and that's really the key different so a mutable object can be freely modified and an IM immutable object can't now what are some examples for mutable objects so a typical mutable object would be a list like we had before could also be um a dictionary so we can change those after the fact or it could also be a set those are all mutable and if you have a custom class that's also mutable by default we can just go in and change attributes on the class now what are some examples for objects that are immutable that can't be freely modified in Python one typical example would be a string so the string 1 2 3 we can't actually reach in and modify um characters in that string so it's immutable another example would be the Tuple that I just showed you or another example could be a frozen set so I'm going to create a frozen set here and the Frozen set well it's frozen so we can't freely modified so those would be examples of immutable objects or immutable values in Python now this seems pretty straightforward right if you have a mutable object you can reach into the object freely modify it and with an immutable object you can't that seems to be a pretty clear definition so 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 so the great thing about an immutable object is that it is sealed it can 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 the bug so essentially when you create an immutable object you will know what its value is going to be and that its value is going to be constant after it was created 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 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 you would always use them if you need to modify an object or a container as you go along right let's let's say you you wrote an algorithm that um 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 the list object um which could be a good thing from a debug ability perspective but um 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 so there can be some performance trade-offs that you need to make so that's just a quick overview of mutability versus immutability and actually what I want to do now is I want to talk about some of the quirks when it comes to immutability in Python so what I'm going to do now is I'm going to create a tuple which is immutable and I'm going to put a list into it which is mutable and we're going to encounter a pretty interesting situation here or well I guess almost a paradox depending on what definition of of mutable and uh immutable you use so I'm going to place some values into this Tuple and at index one I am going to add a list okay so now we looked at this Tuple we've got the Tuple here it starts with the value one and then we've got this list which sits at index one and we've got a string here at uh index two in the Tuple now if I try and modify this Tuple and I go let's say want to try and modify the first value we can't do it right because the Tuple is immutable the same thing is true when I try to let's say um change this string here word uh change it and make it uppercase so if I wanted to do that that doesn't work because strings are immutable too right now you can already see here the type error didn't say hey you can't do that because the Tuple is immutable or does not support item assignment it said the stir object does not support item assignment so can you guess what's going to happen when I try to modify the list at index one so let's say we're going to do the same thing and I'm going to modify this list and so the surprising result here is that this actually worked we modified the T it depends on your defition definition right python says we didn't modify the tupal all the tupal cares about is well it points to some values and one of them is a list and you can't change what list this Tuple is pointing to but because a list is mutable you can very well reach in and modify the list so in a way Python's definition of mutability and immutability is non-transitive so it means if the tupla is immutable that doesn't guarantee that an object referenced by the Tuple is also immutable or that all objects referenced by the Tuple are also immutable so the mutability it kind of stops after the first level right that guarantee stops after the first level so we can't modify the Tuple itself but we can reach in and modify objects that the Tuple holds this can be a little bit confusing when you see it the first time or when you just hear the word immutable and I've you know I've seen this over and over again working with people and also people commenting on my blog posts and tutorials it is just a point of confusion for new python programmers so that's why I decided to do this video so what you can see here is we were able to modify this object even though it is immutable this all comes down to Python's definition of immutability and the fact that immutability in Python is not transitive right it stops after the first level there's no guarantees that further down in the object hierarchy there isn't a mutable object so that's something to keep keep in mind and that's what I meant earlier that sometimes in Python can be a little bit hard to actually write code and use data structures that are always immutable you you really have to be careful not to introduce something like this where you have an immutable data structure that then contains a mutable data structure and that means it can be freely modified and there's no immutability guarantee because immutability is non-transitive all right so not everyone is going to encounter this and um I don't want to discourage you with this video and confuse you but if you do encounter it then you you're going to see you know why it happens you're going to understand why this happens so this is just something to be aware of when it comes to immutability and mutability in Python all right so I hope this video helped you out if you enjoyed this video and you want to see some more python tutorials just like that one then subscribe to my channel the button is in the lower right in this video talk soon and happy python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Real Python · Real Python · 54 of 60

1 A better Python REPL – bpython vs python interpreter
A better Python REPL – bpython vs python interpreter
Real Python
2 Introducing large-type.com – A Utility Website
Introducing large-type.com – A Utility Website
Real Python
3 Reading Hacker News Without Wasting Tons of Time
Reading Hacker News Without Wasting Tons of Time
Real Python
4 Forward References and Python 3 Type Hints
Forward References and Python 3 Type Hints
Real Python
5 Using Sublime Text as your Git Editor
Using Sublime Text as your Git Editor
Real Python
6 Python Code Linting and Auto-Complete for Sublime Text
Python Code Linting and Auto-Complete for Sublime Text
Real Python
7 Make your Python Code More Readable with Custom Exceptions
Make your Python Code More Readable with Custom Exceptions
Real Python
8 Write Better Tests with Sublime Text's Split Layout Feature
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
9 How to Use Sublime Text from the Command Line
How to Use Sublime Text from the Command Line
Real Python
10 Rename Variables with Multiple Selection in Sublime Text
Rename Variables with Multiple Selection in Sublime Text
Real Python
11 Sublime Text Settings for Writing PEP 8 Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
12 Write Cleaner Python with Sublime Text's Indent Guides
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
13 Sublime Text Whitespace Settings for Python Development
Sublime Text Whitespace Settings for Python Development
Real Python
14 Function Argument Unpacking in Python
Function Argument Unpacking in Python
Real Python
15 Python Code Review: Debugging and Refactoring "Conway's Game of Life" +  Automated Tests
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
16 Using "get()" to Return a Default Value from a Python Dict
Using "get()" to Return a Default Value from a Python Dict
Real Python
17 A Python Shorthand for Swapping Two Variables
A Python Shorthand for Swapping Two Variables
Real Python
18 Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
19 Click & Jump to Test Failures from the Command Line (iTerm2)
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
20 Setting up Sublime Text for Python Developers
Setting up Sublime Text for Python Developers
Real Python
21 Sublime Text + Python Guide Overview
Sublime Text + Python Guide Overview
Real Python
22 Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
23 Type-Checking Python Programs With Type Hints and mypy
Type-Checking Python Programs With Type Hints and mypy
Real Python
24 A Shorthand for Merging Dictionaries in Python 3.5+
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
25 Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
26 My Python Code Looks Ugly and Confusing – Help!
My Python Code Looks Ugly and Confusing – Help!
Real Python
27 Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
28 Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
29 Programmer Portfolio – Example and Walkthrough
Programmer Portfolio – Example and Walkthrough
Real Python
30 How to Get Your 1st Speaking Gig at a Tech Conference
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
31 How to Build Your Public Speaking Skills as a Developer
How to Build Your Public Speaking Skills as a Developer
Real Python
32 The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
33 Setting up Sublime Text for Python Developers – Lesson #1
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
34 Cool New Features in Python 3.6
Cool New Features in Python 3.6
Real Python
35 "is" vs "==" in Python – What's the Difference? (And When to Use Each)
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
36 Emulating switch/case Statements in Python with Dictionaries
Emulating switch/case Statements in Python with Dictionaries
Real Python
37 Python Function Argument Unpacking Tutorial (* and ** Operators)
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
38 What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
39 A Crazy Python Dictionary Expression ?!
A Crazy Python Dictionary Expression ?!
Real Python
40 String Conversion in Python: When to Use __repr__ vs __str__
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
41 Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
42 Optional Arguments in Python With *args and **kwargs
Optional Arguments in Python With *args and **kwargs
Real Python
43 Python Context Managers and the "with" Statement (__enter__ & __exit__)
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
44 Installing Python Packages with pip and virtualenv / venv
Installing Python Packages with pip and virtualenv / venv
Real Python
45 "For Each" Loops in Python with enumerate() and range()
"For Each" Loops in Python with enumerate() and range()
Real Python
46 Python Code Review: LibreOffice Automation and the Python Standard Library
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
47 Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
48 Python Tutorial: List Comprehensions Step-By-Step
Python Tutorial: List Comprehensions Step-By-Step
Real Python
49 Leveraging Python's Implicit "return None" Statements
Leveraging Python's Implicit "return None" Statements
Real Python
50 What's the meaning of underscores (_ & __) in Python variable names?
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
51 Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
52 Writing automated tests for Python command-line apps and scripts
Writing automated tests for Python command-line apps and scripts
Real Python
53 How to find great Python packages on PyPI, the Python Package Repository
How to find great Python packages on PyPI, the Python Package Repository
Real Python
Immutable vs Mutable Objects in Python
Immutable vs Mutable Objects in Python
Real Python
55 PyPI vs Warehouse, the Next-Generation Python Package Repository
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
56 pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
57 My Experience at PyCon 2017 in Portland
My Experience at PyCon 2017 in Portland
Real Python
58 Pylint Tutorial – How to Write Clean Python
Pylint Tutorial – How to Write Clean Python
Real Python
59 "Reverse a List in Python" Tutorial: Three Methods & How-to Demos
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
60 Python Refactoring: "while True" Infinite Loops & The "input" Function
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python

This video teaches the fundamentals of immutable and mutable objects in Python, including their definitions, examples, and implications for debugging and parallelism. By understanding these concepts, viewers can improve their Python skills and write more efficient and reliable code.

Key Takeaways
  1. Create a mutable object and an immutable object in Python
  2. Modify the mutable object and observe the result
  3. Try to modify the immutable object and observe the error
  4. Create a tuple with a mutable object and attempt to modify it
  5. Understand the non-transitive property of immutability in Python
💡 Python's immutability is not transitive, meaning that immutable objects can contain mutable objects, which can break immutability guarantees.

Related AI Lessons

I Asked Gemini AI to Preview My Haircut Before My Salon Appointment - Here’s What Happened
Learn how AI can help you preview hairstyles before a salon appointment and make informed decisions
Medium · AI
7 Best AI Tools for Research, Coding, and Development in 2026
Discover the top 7 AI tools for research, coding, and development in 2026, curated from a pool of 47 options, to boost productivity and efficiency
Medium · Data Science
7 Best AI Tools for Research, Coding, and Development in 2026
Discover the top 7 AI tools for research, coding, and development in 2026, curated from a list of 47 tools
Medium · Programming
How to Write a Project Status Report With AI in 15 Minutes
Learn to write a project status report with AI assistance in under 15 minutes, ensuring honesty and accuracy in your reporting
Medium · AI
Up next
I Asked ChatGPT to Apply to 500 Jobs (8 Interviews in 48 Hours)
Sabrina Ramonov 🍄
Watch →