Programming Terms: Mutable vs Immutable

Corey Schafer · Beginner ·⚡ Algorithms & Data Structures ·10y ago

Key Takeaways

The video explains the difference between mutable and immutable objects in programming, using Python as an example. It covers the definitions, examples, and importance of understanding the difference between mutable and immutable objects, including performance implications.

Full Transcript

hey how's it going everybody this is going to be another programming terms video and in this video we're going to look at the terms mutable and immutable so if we look at the definition on Wikipedia it says that an immutable object is an object whose State cannot be modified after it is created this is in contrast to a mutable object which can be modified after it's created um so let's go ahead and look at an example of this and uh why you need to know these two terms now I'm going to be using python uh in these examples but uh like most of my programming term videos don't get caught up in the language I'm using because uh these terms apply to a variety of programming languages so first we're going to take a look at an example of something that is immutable and in Python A String is immutable um so right here you can see that we're setting a equal to the string Corey and if I print out a you can see that I get quy right there um now immutable doesn't mean that I can't assign this variable again uh you can see down here I could change this to John if I run this code you can see that a was equal to Corey now a is equal to John um but you know I said that a was immutable that strings were immutable so what's going on here so what's going on is that it's not actually modifying this string object it's creating a new string object now to um kind of see this in more detail uh python has this ID function which prints out the memory address um so if I save that and now I run this if I run through this code you can see that up here I said that a is equal to Corey I printed out a then I printed out the memory address then I changed it down here and printed out a again and then printed out the memory address again so you can see whenever I changed a here since a string is immutable it created a new string object so you can see here that these uh memory addresses don't match so really to show you that strings are immutable um let's try to change one single character of a so let's say that I want to capitalize Corey so if I said a and the index of zero which would be the c um what if I tried to set this to an uppercase C so let's save that then I'll put back in here print a so let's save that and let's try to run it now you can see here that we get a type error and it says that string object does not support item assignment that's because this is immutable we can't change this string object so what's an example of a an object that is mutable well well in Python a list is mutable so if I make a list here and let's just do 1 2 3 4 5 and then let's comment this out down here for now and let's run this you can see that it uh printed out our list and now if we wanted to change the first value in our list uh let's set it to uh six and we print this out then you can see that it printed out both of the lists and the memory address is the same so it changed that value in place that's what it means to be mutable okay so why is it important to know this why is it important to know the difference between a mutable and an immutable object um well aside from just avoiding errors there's also uh problems with memory as well so some things can seem harmless uh which um really end up being really bad in performance so for example I have this file over here called uh concat dopy and what this does is it has a list of employees here and then it Loops through and this is some sample uh HTML output so let's look at what we're doing in our code here we have this output which is a string uh equal to this opening uh list here and then we are looping through our list of fake employees here and the same output variable we are concatenating these lists with these employees added on to the end and like I said before don't get caught up in the python syntax um just going over these terms here um so then at the very end after we Loop through all the employees and concatenate these strings together then we add on the uh closing list and if I print this out uh you can see that it went through and created some fake HTML here with a list and has our list of employees so what's wrong with doing something like this um because it looks fine and it is fine if you have such a small list here but this is just an example but you know in um in production code you may have uh thousands of strings that you're concatenating and um that's whenever it becomes an issue um so if I uncomment out this line here where I print out the address of output within this for Loop then you can see if I print that out then the address every time it goes through and it adds a new employee to the output then it's creating a new string object so imagine that I had thousands of these then it would be creating thousands of different objects in memory so you can see all these are all different so it's good to keep those the differences between mutable and immutable objects in mind whenever you're thinking about performance also and like I said you'll see this in other other languages also so for example in Java you have a string class uh which is immutable and then you have something I think it's called string buffer which is mutable and it's used for the same thing uh so whenever you're doing large amounts of concatenation and things like that in Java you would want to use a string buffer instead of a string because it doesn't take that performance hit whenever uh of creating uh thousands and thousands of new string objects in memory so hopefully after watching this video you have a better idea of what mutable and immutable means and also some of the things that you need to watch out for once you do understand those differences but if you do have any questions just ask in the comments section below um be sure to subscribe for future videos like this and uh thank you guys for watching

Original Description

In this programming terms video, we will be going over the difference between mutable and immutable objects. An immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created. Let's take a look at some examples as to what exactly this means and why it is important to know. The code from this video can be found at: https://github.com/CoreyMSchafer/code_snippets/tree/master/Mutable ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Corey Schafer · Corey Schafer · 40 of 60

1 Web fonts using CSS Font Face
Web fonts using CSS Font Face
Corey Schafer
2 Using Font Awesome in Desktop Applications (OS X)
Using Font Awesome in Desktop Applications (OS X)
Corey Schafer
3 Sublime Text 2: Setup, Package Control, and Settings
Sublime Text 2: Setup, Package Control, and Settings
Corey Schafer
4 ArcGIS API for JavaScript Part 1: Our First Web Map
ArcGIS API for JavaScript Part 1: Our First Web Map
Corey Schafer
5 Mac Tip: Windows' Snapping Feature on Mac with HyperDock
Mac Tip: Windows' Snapping Feature on Mac with HyperDock
Corey Schafer
6 Linux/Mac Terminal Tutorial: Creating Aliases for Commands
Linux/Mac Terminal Tutorial: Creating Aliases for Commands
Corey Schafer
7 ArcGIS API for JavaScript Part 2: Starting Templates
ArcGIS API for JavaScript Part 2: Starting Templates
Corey Schafer
8 Paver Patio Time Lapse
Paver Patio Time Lapse
Corey Schafer
9 Mac Tip: Ways to perform Screen Capturing and Screenshots
Mac Tip: Ways to perform Screen Capturing and Screenshots
Corey Schafer
10 WordPress Plugins: Imsanity
WordPress Plugins: Imsanity
Corey Schafer
11 WordPress Tips: Test your theme with Theme Unit Test and Monster Widget
WordPress Tips: Test your theme with Theme Unit Test and Monster Widget
Corey Schafer
12 Sublime Text 3: Setup, Package Control, and Settings
Sublime Text 3: Setup, Package Control, and Settings
Corey Schafer
13 Understanding Binary, Hexadecimal, Decimal (Base-10), and more
Understanding Binary, Hexadecimal, Decimal (Base-10), and more
Corey Schafer
14 Mac Tip: Adding Folder Stacks to the Dock
Mac Tip: Adding Folder Stacks to the Dock
Corey Schafer
15 CSS Tips and Tricks: Add External URLs to Print Stylesheets
CSS Tips and Tricks: Add External URLs to Print Stylesheets
Corey Schafer
16 JavaScript Arrays: Properties, Methods, and Manipulation (Part 7 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 7 of 7)
Corey Schafer
17 JavaScript Arrays: Properties, Methods, and Manipulation (Part 1 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 1 of 7)
Corey Schafer
18 JavaScript Arrays: Properties, Methods, and Manipulation (Part 5 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 5 of 7)
Corey Schafer
19 JavaScript Arrays: Properties, Methods, and Manipulation (Part 4 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 4 of 7)
Corey Schafer
20 JavaScript Arrays: Properties, Methods, and Manipulation (Part 3 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 3 of 7)
Corey Schafer
21 JavaScript Arrays: Properties, Methods, and Manipulation (Part 2 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 2 of 7)
Corey Schafer
22 JavaScript Arrays: Properties, Methods, and Manipulation (Part 6 of 7)
JavaScript Arrays: Properties, Methods, and Manipulation (Part 6 of 7)
Corey Schafer
23 Python Tutorial: if __name__ == '__main__'
Python Tutorial: if __name__ == '__main__'
Corey Schafer
24 Sublime Text Quick Tip: "Go To Definition" Click Shortcut
Sublime Text Quick Tip: "Go To Definition" Click Shortcut
Corey Schafer
25 How to quickly create favicons for the desktop, Apple/Android devices, tablets, and more
How to quickly create favicons for the desktop, Apple/Android devices, tablets, and more
Corey Schafer
26 Easily Resize Multiple Images Using Picasa
Easily Resize Multiple Images Using Picasa
Corey Schafer
27 Easily Resize Multiple Images Using the Mac Terminal
Easily Resize Multiple Images Using the Mac Terminal
Corey Schafer
28 Python Tutorial: virtualenv and why you should use virtual environments
Python Tutorial: virtualenv and why you should use virtual environments
Corey Schafer
29 Python Tutorial: pip - An in-depth look at the package management system
Python Tutorial: pip - An in-depth look at the package management system
Corey Schafer
30 Git Tutorial: Using the Stash Command
Git Tutorial: Using the Stash Command
Corey Schafer
31 How Software Engineers, Developers, and Designers can volunteer their skills
How Software Engineers, Developers, and Designers can volunteer their skills
Corey Schafer
32 Git Tutorial: Diff and Merge Tools
Git Tutorial: Diff and Merge Tools
Corey Schafer
33 Git Tutorial: Change DiffMerge Font-Size on Mac OSX
Git Tutorial: Change DiffMerge Font-Size on Mac OSX
Corey Schafer
34 Sublime Text Quick Tip: Launch Sublime Text from the Terminal
Sublime Text Quick Tip: Launch Sublime Text from the Terminal
Corey Schafer
35 Python Tutorial: str() vs repr()
Python Tutorial: str() vs repr()
Corey Schafer
36 Programming Terms: DRY (Don't Repeat Yourself)
Programming Terms: DRY (Don't Repeat Yourself)
Corey Schafer
37 Programming Terms: String Interpolation
Programming Terms: String Interpolation
Corey Schafer
38 Programming Terms: Idempotence
Programming Terms: Idempotence
Corey Schafer
39 Python Tutorial: Namedtuple - When and why should you use namedtuples?
Python Tutorial: Namedtuple - When and why should you use namedtuples?
Corey Schafer
Programming Terms: Mutable vs Immutable
Programming Terms: Mutable vs Immutable
Corey Schafer
41 Python Tutorial: Else Clauses on Loops
Python Tutorial: Else Clauses on Loops
Corey Schafer
42 Overview of Online Learning Resources
Overview of Online Learning Resources
Corey Schafer
43 Mac OS X Terminal Tutorial: Time-Saving Keyboard Shortcuts
Mac OS X Terminal Tutorial: Time-Saving Keyboard Shortcuts
Corey Schafer
44 Git Tutorial for Beginners: Command-Line Fundamentals
Git Tutorial for Beginners: Command-Line Fundamentals
Corey Schafer
45 Quickest and Easiest Way to Run a Local Web-Server
Quickest and Easiest Way to Run a Local Web-Server
Corey Schafer
46 Python Tutorial: Generators - How to use them and the benefits you receive
Python Tutorial: Generators - How to use them and the benefits you receive
Corey Schafer
47 Python Tutorial: Comprehensions - How they work and why you should be using them
Python Tutorial: Comprehensions - How they work and why you should be using them
Corey Schafer
48 Chrome Quick Tip: Quickly Bookmark Open Tabs for Later Viewing
Chrome Quick Tip: Quickly Bookmark Open Tabs for Later Viewing
Corey Schafer
49 Programming Terms: Combinations and Permutations
Programming Terms: Combinations and Permutations
Corey Schafer
50 Git Tutorial: Difference between "add -A", "add -u", "add .", and "add *"
Git Tutorial: Difference between "add -A", "add -u", "add .", and "add *"
Corey Schafer
51 Preparing for a Python Interview: 10 Things You Should Know
Preparing for a Python Interview: 10 Things You Should Know
Corey Schafer
52 SQL Tutorial for Beginners 1: Installing PostgreSQL and Creating Your First Database
SQL Tutorial for Beginners 1: Installing PostgreSQL and Creating Your First Database
Corey Schafer
53 SQL Tutorial for Beginners 2: Creating Your First Table
SQL Tutorial for Beginners 2: Creating Your First Table
Corey Schafer
54 SQL Tutorial for Beginners 3: INSERT - Adding Records to Your Database
SQL Tutorial for Beginners 3: INSERT - Adding Records to Your Database
Corey Schafer
55 Linux/Mac Terminal Tutorial: Navigating your Filesystem
Linux/Mac Terminal Tutorial: Navigating your Filesystem
Corey Schafer
56 Python: Ex Machina Easter Egg - Hidden Message within the Code
Python: Ex Machina Easter Egg - Hidden Message within the Code
Corey Schafer
57 Mac Tip: New Split Screen Feature in El Capitan
Mac Tip: New Split Screen Feature in El Capitan
Corey Schafer
58 Setting up a Python Development Environment in Eclipse
Setting up a Python Development Environment in Eclipse
Corey Schafer
59 Git Tutorial: Fixing Common Mistakes and Undoing Bad Commits
Git Tutorial: Fixing Common Mistakes and Undoing Bad Commits
Corey Schafer
60 SQL Tutorial for Beginners 4: SELECT - Retrieving Records from Your Database
SQL Tutorial for Beginners 4: SELECT - Retrieving Records from Your Database
Corey Schafer

This video teaches the difference between mutable and immutable objects in programming, with a focus on Python. It covers examples, performance implications, and best practices for working with mutable and immutable objects.

Key Takeaways
  1. Define mutable and immutable objects
  2. Understand the difference between mutable and immutable objects in Python
  3. Learn how to use the ID function to print memory addresses
  4. Practice modifying mutable and immutable objects
  5. Understand the performance implications of concatenating strings
  6. Apply knowledge of mutable and immutable objects to real-world scenarios
💡 Understanding the difference between mutable and immutable objects is crucial for writing efficient and effective code, as it can significantly impact performance and memory usage.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →