Mutability revisited - Python 3 Programming Tutorial p.8

sentdex · Beginner ·🛠️ AI Tools & Apps ·7y ago

Key Takeaways

The video covers mutability in Python 3, discussing how mutable and immutable objects work, and how to modify them within functions. It uses Python 3 as the primary tool for demonstration.

Full Transcript

what's going on everybody and welcome to part 8 of our Python 3 basics tutorial series in this video what we're gonna be talking about is kind of revisiting the concept of mutability because I think it's pretty important that we don't get through the basic series using the methodology though we're using and not address mutability I'm not sure if that logically made sense that string there but basically the way that we're doing things right now is is we're modifying this game this game variable outside of this function here and we're able to do that because it's mutable but this can be very tricky at times and later on if you continue to code with the assumption that that's gonna work out for you eventually you're gonna hit a wall and it's not gonna feel good and you're not gonna understand like why you're hitting this wall and it's like the most frustrating thing in the world when you believe you're like rereading your code you're like I've done this a million times why isn't this working this is logical ice is so simple and you're gonna just be pulling out your hair so so I think I would be doing a pretty big disservice if I didn't at least bring it up because it's probably not gonna come up again and arguably I don't think this has ever come up in any tutorial I've never really addressed this but it can bite you so let's talk about it so so sometimes you might see so like if you want to modify a value outside of a function if it's a list of lists we can at least do one thing and that is set a value remember that set a value in that list of lists ok we're getting away with that we can do that but that's not the case for everything that we could plausibly be working with so so what I'm gonna do is I think for now I think what I'd like to do is I'm going to comment this out and then we're gonna show some examples and I'm gonna show you what I think would be a superior method of kind of building these kinds of things so first of all I'll just comment those out multi-line comment make some space and and in fact what I'll do is I'm gonna copy all of this I'm just gonna copy that up here paste and then we're gonna run a game board just play just display true for now and in fact actually we can just run game board because that it won't matter for the purposes here and let's run that okay so that works right now I guess I am going to make the change that I wanted to make but basically we want this function to eventually return return game board but game board is printing so maybe what instead what I'd like to do is let's print this is challenging cuz I'm trying to show I want to show an exact change yeah that's okay so so anyways game board we print game board and we can see no change has been made and then if we rate word run player 1 Row 1 column 1 and what if we we can print game here and then after running game board we can print game again so we'll have like three games basically and we can see initially okay and then here's the pretty modified version and then here is after the function has run yet again a version where that one is indeed modified in there now what I'd like to do is change this so we're going to change first the variable here of game and we're going to make it instead of string I want to play a game and now what I'd like to do is take game board we're gonna get rid of all of the parameters but none of these parameters were important we weren't like passing we were never passing game into here anyways these were just going to be used later and in fact we actually could leave these here because we don't we're not even gonna use them and that's fine we can leave them there and instead what I'm going to do is I'm just going to remove this code here and all I want to do now is change game to be a game now knowing what you know what's gonna happen when we run game board and just to keep things clean I'm gonna remove that just so it's a little simpler but you're probably expecting game to end being called a game let's go ahead and run it though and we can see here no that's not true what if we print game here because a moment ago we were somehow able to access the game but now we're unable to access game early on so immediately we know something is afoot and let me run this again and then so but then what if we print a game after we've set a game okay so we're thinking where everything's good at this point and then we get down here and we're back to I want to play a game that's because this string is immutable we can't be we can't go and change that so so this can start to kind of run you into some trouble later on so like what if we were to do this so what if we said print and one thing we can do is we can always check the unique ID of a element in Python using the built-in function ID so we'll check the ID of game here and then we can check the ID of game here and then maybe at the very end again so start thinking about okay what do you think which IDs are going to be the same do you think this and this ID will be the same or this and this ID or all three will be different and so on okay so we can see here the first idea let's say ends and 152 the next ID ends in 376 what about I'm sorry the first one sorry guys the first one ends in 376 the next one ends in 152 and then it finally it ends in 376 so basically from the beginning this function never actually modified the value of game in the beginning and that's a pretty big deal so so let's go back to playing with lists then shall we so let's do well print game I don't want to print the IDS anymore for now I don't think and in fact let me just comment that out because we'll come back to printing the idea of game but right now I just don't really want them pasted there and I'm gonna get rid of that one actually we should leave it I'll comment that out so then what if we change game to be now a list one two and three and then game what if now we just try it what if we try to call game a list at this point what happens we got one two three we change it to be a game or so we thought right wasn't this supposed to be mutable we were just seeing examples of it being mutable moments ago right now we've got game equals a game we print oh we never ran let's run game board game board there we go okay we we run here we do print game here and sure enough it says a game but still at the end we get one two three so it still didn't get modified despite us thinking wait a second wasn't this moments ago a list of lists seemed to be mutable right well what about game one equals 99 now what happens now we see oh we have modified the initial one now because it again here if we were to print let's print the IDs see that they changed IDs but if we just simply oh no okay good yeah I thought we were gonna get in trouble there wow I'm definitely hitting why and it's not going in my favor okay anyways game one equals 99 run that again let's see what have we done wrong here prints game hold on why are you still see I feel like it's still defying me and this time it shouldn't be defined this way are we not running okay we're not running game board I see game board I'm confusing myself Oh like wait a second okay so printing out game again we can see here it does indeed modify it so what are we able to do we're able to modify right we're able to modify that that that objects so we can we can change the value of that object but can we change the object itself no okay so that can get us into some some serious trouble down the line now the last thing I want to do and last time I tried to do this we got into trouble let's see if I can get away with I'm trying to get back to I want to play a game cool and we stay with I want to play a game one more thing for me to show you guys is we can actually global game and so if we say clips so global oh my gosh global game what this does is it sets game to be a globally accessible and manipulable manipulatable anyways it's not just to be a global value that we can start modifying from within this function it's going to affect that variable name globally so the way that's going to work is we will be able to modify game now so for example if we run this weave global game we're not passing game board of course I continue to run into that and I keep trying to run it and I'm like wait it's not doing what I said it was gonna do okay now okay now it has been modified to be a game and it gets a new ID and all that and then if we were to print game down below here print ID of game we see that it retains the new game value that it got from the game function but at the same time even though that that has happened it also has modified this initial it literally changed that variable up above okay so a lot of stuff to unpack there for sure I also have passed in the text-based version of this tutorial I put in a little a little quiz and that Daniel or danos from the discord wrote up and I think it's actually a pretty good quiz on so if you want I'll have the link to the text-based version of this tutorial in the description go there and like copy and paste this code into like some script or something and beside all the X's are on a sheet of paper or whatever say okay here's what I think X is going to be equal to right and then run it and see how you did even after like seven years of Python I still missed one of them it was uh I don't really want to talk about it necessarily but it was this one here and at least I think it was it was the I want to say was the middle one yeah okay it was that one and you know maybe for you guys or people that are following along that have nothing to do with basics maybe you miss nothing on this test but my argument is if you missed anything on this little quiz or you had to think kind of hard about it chances are when you're like zooming through writing a program that's how I program by the way you are highly likely to make the mistake so the whole point of this tutorial has been one to draw your attention to how you can run yourself amok with mutability but also I would argue we should go ahead and just pass game here or maybe better put let's call it game map or apparently game board where did that come let's name of the function let's not do that so we'll call it game map so we pass game map I would argue let's go ahead and call this game map so we're going to modify this temporary game map variable here game map game map enumerate game map and then when we're all done return game map now again in this exact problem in this exact code this is not really doing anything special for you but unless you can write perfect code or take that quiz and get it right every time and always never make that mistake I'm just gonna argue that maybe you want to get in the habit of doing things this way or do you want to check it every time but in general this is the way I would just write everything it may not be necessary to do it in all cases but I would do that and honestly I went through a good probably four or five years of Python before I realized there was a thing going on there and I just always wrote code this way and you know what it never got me in trouble so anyway just gonna share that I know I'm confident some people are gonna disagree with that methodology and if you do disagree that's all right write it however you want to write it but in this case if we're going to say game map and then return game map we will always want to say something like this game equals game board and then game equals game board when you want to play and let me just run that real quick okay what's our error this is zoomed in like way too much for me type error missing one oh we're not packing we didn't pass the actual game map okay so game and then we pass game okay and now everything acts in the exact same way so the idea here is you pass the game map or whatever object you're attempting to manipulate with your function you pass it you modify that temporary you know parameter value or variable and then you return it when you're done and then when you're using it you say the thing that you're attempting to modify equals the result of that thing and you pass that thing and all that so in terms of efficiency I haven't run it so if you wanted if you were looking to scale a program to like you know millions of connections at a specific time this may not be the best way to do that but a lot of code isn't like that so and this is really just a basics tutorial but I would take that into consideration in terms of how you should be doing it on obviously if the thing is immutable we can't do it like with a string or something like that then you will have to treat it this way but if you have something like this where we're just trying to modify a certain value in a list of lists no it's not required but if you go through your programming tutorial thinking you can do everything this way you're going to quickly find out no no no you may not do it that way so anyways pretty long tutorial on that but it needed to be covered like I said definitely check out the quiz that's in the text-based it's just kind of a good little quick quick test to see see if you understand it and if you don't come to the help help channel in the discord GG sent X and somebody there will be happy to explain something if you are confused and finally a quick shout out to my most recent awesome awesome channel members we've got fluff Bill Michael Newman and ace Rider thank you guys very much for your support it allows me to do videos just like this one so I really appreciate it I hope everybody has enjoyed and I will see you in the next video

Original Description

In this part, we're going to revisit the topic of mutable and immutable objects. This concept is masked pretty well in Python, which, like dynamic typing, can be great... or not. It can really bite you one day if you don't have a good understanding of how it works, so let's talk about it. Playlist: https://www.youtube.com/playlist?list=PLQVvvaa0QuDeAams7fkdcwOGBpGdHpXln #python #programming #tutorial quiz: x = 1 def test(): x = 2 test() print(x) x = 1 def test(): global x x = 2 test() print(x) x = [1] def test(): x = [2] test() print(x) x = [1] def test(): global x x = [2] test() print(x) x = [1] def test(): x[0] = 2 test() print(x)
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from sentdex · sentdex · 0 of 60

← Previous Next →
1 Matplotlib Python Tutorial Part 1: Basics and your first Graph!
Matplotlib Python Tutorial Part 1: Basics and your first Graph!
sentdex
2 Python Encryption Tutorial with PyCrypto
Python Encryption Tutorial with PyCrypto
sentdex
3 Python's Logging Function
Python's Logging Function
sentdex
4 wxPython Tutorials 1: Making Windows GUIs with Python : Installing + 1st window!
wxPython Tutorials 1: Making Windows GUIs with Python : Installing + 1st window!
sentdex
5 wxPython Tutorials 2: Making Windows GUIs with Python: Customizing Window Parameters
wxPython Tutorials 2: Making Windows GUIs with Python: Customizing Window Parameters
sentdex
6 wxPython Programming Tutorial 3: Menu Bar and Menu Button
wxPython Programming Tutorial 3: Menu Bar and Menu Button
sentdex
7 wxPython Programming Tutorial 4: Panels
wxPython Programming Tutorial 4: Panels
sentdex
8 wxPython Programming Tutorial 5: User Input Saved To Variables
wxPython Programming Tutorial 5: User Input Saved To Variables
sentdex
9 wxPython Programming Tutorial 6: Multiple Choice Input
wxPython Programming Tutorial 6: Multiple Choice Input
sentdex
10 wxPython Programming Tutorial 7: Adding Static Text and Colors
wxPython Programming Tutorial 7: Adding Static Text and Colors
sentdex
11 wxPython Programming Tutorial 8: Custom Button Images
wxPython Programming Tutorial 8: Custom Button Images
sentdex
12 wxPython Programming Tutorial 9: Tool Bar Items and Sub Menus!
wxPython Programming Tutorial 9: Tool Bar Items and Sub Menus!
sentdex
13 Basic PHP Tutorial 13: Multi-dimensional Array
Basic PHP Tutorial 13: Multi-dimensional Array
sentdex
14 Basic PHP Tutorial 15: Functions and Global Variables
Basic PHP Tutorial 15: Functions and Global Variables
sentdex
15 Basic PHP Tutorial 12: Associative Array
Basic PHP Tutorial 12: Associative Array
sentdex
16 Basic PHP Tutorial 14: Foreach loop
Basic PHP Tutorial 14: Foreach loop
sentdex
17 Basic PHP Tutorial 16: Include and Require
Basic PHP Tutorial 16: Include and Require
sentdex
18 Basic PHP Tutorial 7: Assignment, comparison and Logical operators
Basic PHP Tutorial 7: Assignment, comparison and Logical operators
sentdex
19 Basic PHP Tutorial 4: Variables and Comments
Basic PHP Tutorial 4: Variables and Comments
sentdex
20 Basic PHP Tutorial 11: Arrays part 1, basic array
Basic PHP Tutorial 11: Arrays part 1, basic array
sentdex
21 Basic PHP Tutorial 6: If else and else if conditionals cont'd
Basic PHP Tutorial 6: If else and else if conditionals cont'd
sentdex
22 Basic PHP Tutorial 1: Intro to PHP
Basic PHP Tutorial 1: Intro to PHP
sentdex
23 Basic PHP Tutorial 3: HTML with PHP
Basic PHP Tutorial 3: HTML with PHP
sentdex
24 Basic PHP Tutorial 9: While Loop
Basic PHP Tutorial 9: While Loop
sentdex
25 Basic PHP Tutorial 10: Switch Statement
Basic PHP Tutorial 10: Switch Statement
sentdex
26 Basic PHP Tutorial 2: Print and Echo
Basic PHP Tutorial 2: Print and Echo
sentdex
27 Basic PHP Tutorial 5: If else and else if conditional statements
Basic PHP Tutorial 5: If else and else if conditional statements
sentdex
28 Basic PHP Tutorial 8: Arithmatic Operators: Doing math with php
Basic PHP Tutorial 8: Arithmatic Operators: Doing math with php
sentdex
29 Basic PHP Tutorial 17: User Input Form Example / String Manipulation
Basic PHP Tutorial 17: User Input Form Example / String Manipulation
sentdex
30 Basic PHP Tutorial 18: HTML Entities and forms cont'd
Basic PHP Tutorial 18: HTML Entities and forms cont'd
sentdex
31 Basic PHP Tutorial 19: Finding words in strings
Basic PHP Tutorial 19: Finding words in strings
sentdex
32 Basic PHP Programming Tutorial 20: Saving to a File / writing and appending
Basic PHP Programming Tutorial 20: Saving to a File / writing and appending
sentdex
33 Basic PHP Programming Tutorial 22: Hashing part 2: salting
Basic PHP Programming Tutorial 22: Hashing part 2: salting
sentdex
34 Basic PHP Programming Tutorial 23: Variables in Strings and tokenizing
Basic PHP Programming Tutorial 23: Variables in Strings and tokenizing
sentdex
35 Basic PHP Programming Tutorial 21: MD5 Hashing For Security
Basic PHP Programming Tutorial 21: MD5 Hashing For Security
sentdex
36 Basic PHP Programming Tutorial 24: String similarity
Basic PHP Programming Tutorial 24: String similarity
sentdex
37 Basic PHP Programming Tutorial 25: Time and Time stamps
Basic PHP Programming Tutorial 25: Time and Time stamps
sentdex
38 Basic PHP Programming Tutorial 26: Die and Exit
Basic PHP Programming Tutorial 26: Die and Exit
sentdex
39 Basic PHP Programming Tutorial 27: MySQL Databases Part 1
Basic PHP Programming Tutorial 27: MySQL Databases Part 1
sentdex
40 Basic PHP Programming Tutorial 28: MySQL Database Part 2: Reading From Database
Basic PHP Programming Tutorial 28: MySQL Database Part 2: Reading From Database
sentdex
41 Basic PHP Programming Tutorial 29: MySQL Database Part 3: Inputting Data
Basic PHP Programming Tutorial 29: MySQL Database Part 3: Inputting Data
sentdex
42 Basic PHP Programming Tutorial 30: MySQL database in Use
Basic PHP Programming Tutorial 30: MySQL database in Use
sentdex
43 Django Tutorial Web Development with Python Part 1: Installing Django
Django Tutorial Web Development with Python Part 1: Installing Django
sentdex
44 Python Tutorial: File Deletion and Folder Deletion / directory deletion
Python Tutorial: File Deletion and Folder Deletion / directory deletion
sentdex
45 Python Tutorial: How to Rename Files and Move Files with Python
Python Tutorial: How to Rename Files and Move Files with Python
sentdex
46 3D Graphs in Matplotlib for Python: Basic 3D Line
3D Graphs in Matplotlib for Python: Basic 3D Line
sentdex
47 3D Plotting in Matplotlib for Python: 3D Scatter Plot
3D Plotting in Matplotlib for Python: 3D Scatter Plot
sentdex
48 3D Charts in Matplotlib for Python: Multiple datasets scatter plot
3D Charts in Matplotlib for Python: Multiple datasets scatter plot
sentdex
49 Sikuli Tutorial 1: Visually programming in python!
Sikuli Tutorial 1: Visually programming in python!
sentdex
50 Sikuli Tutorial 2: Program visually in python!
Sikuli Tutorial 2: Program visually in python!
sentdex
51 Sikuli Tutorial 3: Program visually in python!
Sikuli Tutorial 3: Program visually in python!
sentdex
52 3D Bar Charts in Python and Matplotlib
3D Bar Charts in Python and Matplotlib
sentdex
53 3D Plane wire frame Graph Chart in Python
3D Plane wire frame Graph Chart in Python
sentdex
54 Raspberry Pi Part 1 Introduction
Raspberry Pi Part 1 Introduction
sentdex
55 Raspberry Pi Part 8: First Download and Update! (Firmware)
Raspberry Pi Part 8: First Download and Update! (Firmware)
sentdex
56 Raspberry Pi Part 10: How to set up a Linux Web Server on your Pi
Raspberry Pi Part 10: How to set up a Linux Web Server on your Pi
sentdex
57 Raspberry Pi Part 11: Remote Desktop
Raspberry Pi Part 11: Remote Desktop
sentdex
58 Twitter Analysis: How to rank a user's influence
Twitter Analysis: How to rank a user's influence
sentdex
59 GPIO Tutorial for Pi Part 2 - Programming the GPIO
GPIO Tutorial for Pi Part 2 - Programming the GPIO
sentdex
60 GPIO Tutorial for Raspberry Pi Part 1 - Setting up
GPIO Tutorial for Raspberry Pi Part 1 - Setting up
sentdex

This video teaches the concept of mutability in Python 3, covering how to modify mutable and immutable objects within functions, and how to use global variables effectively. It provides a comprehensive understanding of variable modification and scope in Python.

Key Takeaways
  1. Comment out the original code
  2. Copy and paste the original code
  3. Run the game board function
  4. Print the game board
  5. Modify the game variable
  6. Use the ID function to check unique IDs
  7. Create a list in Python and modify its elements
  8. Modify the game variable to be a game and get a new ID
  9. Print the ID of game and retain the new game value
  10. Change the initial variable value when modifying the global game variable
💡 Understanding mutability in Python is crucial for effective variable modification and scope management, and can help prevent unexpected behavior in code.

Related AI Lessons

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