Mutability revisited – Python 3 Programming Tutorial p.8

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)

68 comments

  1. Carlos Fernรกndez on

    sentdex hopefully you realize that many of us just find your videos on the RSS feed – but we follow the link and we find that the video is not yet available, which is quite annoying. Unless there’s a feed for the actually available videos. Otherwise the RSS feed is useless.

    Reply
  2. Zarren Spry on

    YouTube premieres are pretty lame. It’s like rolling a fat joint and just before you light it realising you don’t have a lighter. Love your videos Sentdex, you’re the man but I detest YouTube Premier. Haven’t you noticed a drop in traffic to these videos?

    Reply
  3. Alex on

    It is the fith time I missclick the video because I see it in my log but I don’t notice you have not already publish it. They should not appear with the rest of the videos but in a separate view to keep track ; it would be much more comfortable

    Reply
  4. Astraea Artemis on

    Hey sendtex thank you so much for everything. I started my python and ml journey from ur channel. Well i got 150% hike from my new company. Thanks to you i can say i work im data ๐Ÿ˜˜๐Ÿ˜˜๐Ÿ˜˜๐Ÿ˜˜

    Reply
  5. Poop Queen on

    Hey sendtex thank you so much for everything. I started my python and ml journey from ur channel. Well i got 150% hike from my new company. Thanks to you i can say i work im data ๐Ÿ˜˜๐Ÿ˜˜๐Ÿ˜˜๐Ÿ˜˜

    Reply
  6. IM Ma Fav on

    Hey sendtex thank you so much for everything. I started my python and ml journey from ur channel. Well i got 150% hike from my new company. Thanks to you i can say i work im data ๐Ÿ˜˜๐Ÿ˜˜๐Ÿ˜˜๐Ÿ˜˜

    Reply
  7. yan ziselman on

    i wonder whether properties of classes are treated as “global” variables when you pass self to a function defined in the class. Every time i wrote a class i assumed it is so and it worked. i hope this habit won’t bite me in the ass one day.

    Reply
  8. dragonfire on

    sentdex….i owe a lot to you. A CEO once linked your channel on quora and I followed your channel to learn. I applied as an intern to the CEO’s startup and got accepted. I even transitioned into a well paying full time position too. Thanks man and I hope you make great progress through this channel and help many others.

    Reply
  9. prasanth malla on

    sentdex….i owe a lot to you. A CEO once linked your channel on quora and I followed your channel to learn. I applied as an intern to the CEO’s startup and got accepted. I even transitioned into a well paying full time position too. Thanks man and I hope you make great progress through this channel and help many others.

    Reply
  10. prasanth on

    sentdex….i owe a lot to you. A CEO once linked your channel on quora and I followed your channel to learn. I applied as an intern to the CEO’s startup and got accepted. I even transitioned into a well paying full time position too. Thanks man and I hope you make great progress through this channel and help many others.

    Reply
  11. KiloSierraAlpha on

    Every time I miss first 5-10 min of these videos, I lose the will to watch it. Please do normal videos. If you wanna do live streaming, that’s great. But this premiere thing is just irritating ๐Ÿ™ Thanks sentdex!

    Reply
  12. f0restw0w on

    After I’ve watched a “premiered” video it doesn’t show up as “watched” with a completed red bar at the bottom of the thumbnail in my subscription feed. I don’t know if that’s intended but it’s quite annoying.

    Reply
  13. Hawkeye ZAR on

    Love your videos dude, not sure why people complain about premiere. Think some people just have nothing to do but complain and cry.
    You are one of the few youtubers that don’t flood my screen with ads. So having to wait and extra day to watch your videos is worth it.

    People are just so ungrateful for the free knowledge that you provide. I bet you these are the same people that use ad block for youtube ads on other channels.

    Reply
  14. Edster on

    I found this video slightly confusing, why not just say a string literal is immutable and a list is mutable, then give some simple examples of each, then explain how scope works and explain how that can break your code.

    Like your videos a lot, just felt I needed to speak up on this one though haha

    Reply
  15. Ciccio&Bombo on

    This is why python REALLY needs a declaring variable sytanx.
    The problem of “why isn’t this being changed” is because python thinks you are declaring a new variable inside the function since by default it doesn’t access global variables. Of course you can’t declare a variable when using the [ ] operator, so it will try to find a global variable for that.

    With a keyword like “let” it would be crystal clear what is being created or accessed, and the interpreter could yell at you if you try to access a global variable without saying it, instead of silently creating a new one

    Reply
  16. Lank Asif on

    sentdexย  I particularly loved this tutorial, partly because it was longer but mostly because of the way you took the time to outline and exhibit a common but tricky to grasp topic. Thanks again for all your hard work and dedication to helping those that need it.
    Cheers!

    Reply
  17. TheSaver on

    good stuff mate, i just started learning python like 2 days ago (coming from ADF/android development background ) and your videos are just different and more exciting to watch and learn from than other sources, i just want u to know this is the best tutorials ive seen on youtube, i usually check youtube for the topics i wanna learn and find nothing that much valuable and get back to learning from the good old docs, but this is actually entertaining and informative at the same time, thank you so much for your work <3 keep em coming.

    Reply
  18. CreepersHunter on

    Hi, Iโ€™m getting a bit confused on line 8 and 9. Shouldnโ€™t the โ€˜if not just_displayโ€™ run the code on line 9 if it is NOT false (not just_display)?

    Reply
  19. wasim shoman on

    Man I love your videos. I learned a lot from your series on machine learning using python. Now I watch everything you share on YouTube. I love your way of teaching us. Best

    Reply
  20. dotanuki on

    I gotta go, so only watched to ~8:00 but

    Dude, that is not what mutability/immutability is. The reason your game variable isn’t reassigned to “A game’ is because you declare a function-local variable, shadowing the one in the outer scope. If you insert the line ‘global game’ in the function above your assignment, what happens, and why?

    In ruby, you can append to a string (with the << operator) and the string retains the same object id. Ruby has mutable strings. In python, appending to a string (with the += operator ) makes a new string with a new id under the hood, because it has immutable strings.

    Reply
  21. dotanuki on

    I gotta go, so only watched to ~8:00 but

    Dude, that is not what mutability/immutability is. The reason your game variable isn’t reassigned to “A game’ is because you declare a function-local variable, shadowing the one in the outer scope. If you insert the line ‘global game’ in the function above your assignment, what happens, and why?

    In ruby, you can append to a string (with the << operator) and the string retains the same object id. Ruby has mutable strings. In python, appending to a string (with the += operator ) makes a new string with a new id under the hood, because it has immutable strings. EDIT: Ok I just watched the whole thing, you did the global directive, but that's a concern of scope and assignment, not mutability. Mutability has to do whether you can modify a value. In modern javascript you can declare a constant variable with const a = [], and trying to reassign a will be an error, but the value of a can be modified. So a is not assignable but mutable. Even if a pure functional language will have all variables be constants and datastructures be immutable, scope, 'assignibility/constness' and mutability are separate concerns. If you want your game_board() function to be pure and treat your game table as immutable, you'd need to create a copy of it in the function and return the modified copy. Now you're still modifying the game table that gets passed in.

    Reply
  22. Ben on

    The video appears in my feed when it is not available yet and doesn’t when it is. I had to search for this video manually through the playlist. I have nothing against Premiere but most of your viewers are asynchronous and I believe it will drive your views down.

    Reply
  23. John Walton on

    this video prob saved all together several years worth of time collectively, that’s a serious concept that can slip by and become a nightmare of a problem,

    Reply
  24. Species 8472 on

    this video prob saved all together several years worth of time collectively, that’s a serious concept that can slip by and become a nightmare of a problem,

    Reply
  25. PostHumanOriented 8472-1488 on

    this video prob saved all together several years worth of time collectively, that’s a serious concept that can slip by and become a nightmare of a problem,

    Reply
  26. alphastrata on

    @harrison although I never make it to the live premieres I still think theyโ€™re awesome. YT is great, youโ€™re great, doing this is a great idea so that you can (as you said) interact more with your audience while theyโ€™re consuming your content.

    Reply
  27. Brother Lui on

    Hi, sorry to say but your explanation of accessing and changing outside variables inside functions is not correct. You are mixing object mutability and variable scope. This is misleading.

    Reply
  28. Newton Lomar on

    Omfg, you do a fucking GREAT job for free and people still complaining, holy shit. I mean, I’m a patient person, but even Buddha would get pissed off with this kids. You do an amazing job dude, I will always comeback here!

    Reply
  29. Didier N. on

    I wish I watched this video this weekend! I have been sweating over a global variable for days! Finally got it worked! Thanks for sharing.

    Reply
  30. John Dunn on

    Great tutorial. Took me 90 minutes to work through it and understand what’s happening. That said, it’s making sense. Thank you.

    Reply
  31. Rizqullah T on

    While watching this video I was keep asking myself why do I never counter such problem, but then in the end you mentioned the methodology that you’ve been using for seven years, which exactly what I always do. I am lucky

    Reply
  32. nana kiany on

    I watched lots of tutorials in the big named websites and I paid a lot for those courses, I can absolutely say you are a gifted teacher and I love the way that you explain every thing in an easy way. You are the best and smartest teacher and thanks a lot for your amazing videos.

    Reply
  33. Sreeram P on

    I am trying iterate through the data(elevation) from .hgt file. I have attached the codes which i used to get the elevation from the file.

    from gmalthgtparser import HgtParser

    hgt_file=’N09E076.hgt’

    with HgtParser(hgt_file) as parser:alt = parser.get_elevation((9.666673719181665,76.30757542014408))

    print(alt)

    the output of the above code will be : (1200, 1108, 7)

    So here the input is given by the user with exact longitude and latitude. I want it to iterate through all the coordinates under some range and print each coordinates elevation and it should be saved as an excel file.

    Reply
  34. Francis Lim on

    I tried this and got “UnboundLocalError: local variable ‘x’ referenced before assignment” on line 3
    x = [0]
    def test():
    print(x)
    x = [3]
    print(x)
    test()
    print(x)

    However, if i do this, no error occurs
    x = [0]
    def test():
    print(x)
    x[0] = 3
    print(x)
    test()
    print(x)

    and it prints
    [0]
    [3]
    [3]

    Weird to get an error for the first code but not the second.

    Reply
  35. GB Plays on

    every bit of code works but as soon as i type in an if statement like he did; if not just_display: it doesn’t work…

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Show Buttons
Hide Buttons