Programming Terms: Mutable vs Immutable

Sdílet
Vložit
  • čas přidán 4. 07. 2024
  • 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:
    github.com/CoreyMSchafer/code...
    ✅ Support My Channel Through Patreon:
    / coreyms
    ✅ Become a Channel Member:
    / @coreyms
    ✅ One-Time Contribution Through PayPal:
    goo.gl/649HFY
    ✅ Cryptocurrency Donations:
    Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3
    Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33
    Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot
    ✅ Corey's Public Amazon Wishlist
    a.co/inIyro1
    ✅ Equipment I Use and Books I Recommend:
    www.amazon.com/shop/coreyschafer
    ▶️ You Can Find Me On:
    My Website - coreyms.com/
    My Second Channel - / coreymschafer
    Facebook - / coreymschafer
    Twitter - / coreymschafer
    Instagram - / coreymschafer

Komentáře • 120

  • @matuagify
    @matuagify Před 4 lety +17

    Man, have watched thousands of video's on CZcams. But you are the best . No one explains better than you. I'm glad I I found your channel.

  • @Avarn388
    @Avarn388 Před 4 lety +7

    I already had a good grasp of mutable and immutable, but I'll admit; your explanation definitely made the distinction clear. Especially with regards to how immutable objects occupy a distinct space of memory and how trying to modify them can create multiple objects in memory. Overall, I learned a lot so thank you very much for posting these. :)

  • @waiitwhaat
    @waiitwhaat Před 2 lety +4

    This video feels like finding gold among the archives. Though the tools are outdated (python 2) but the concept remains a timeless asset.

  • @soumyazyx
    @soumyazyx Před 4 lety +16

    Thank you Corey for your time and effort. Keep spreading the knowledge.

  • @psalt21
    @psalt21 Před 7 lety +5

    I wish I could give you more than one thumbs up. Your explanation and example really hit the concept home for me. I hope you can get more views since I think you did a very good job. The final example was a great practical example of how the way it is stored in memory could really affect what you are trying to do - in certain situations mutable is ideal in others immutable will have great advantages. The better you understand the difference between the two the better you can decide the approach to best meet your needs.

  • @markrity
    @markrity Před 8 lety +59

    In your last example of displaying the employees , you said its a bad way to represent a big list of employees , so what would be the right way ?

    • @coreyms
      @coreyms  Před 8 lety +90

      +Mark Davydov It really depends on the scenario for how you would display the list. In the example in the video, the main thing to take away was that the memory address was changing with each iteration. So instead of appending to an output string at each step, we could have instead appended to a result list and then printed out that list after the iteration was complete. And if you only need a simple delimiter when displaying a list, you could use join, e.g. '-'.join(employees)
      So there are several approaches to doing it the correct way based on what you need at the time, but this was more meant to show why this approach wouldn't be the best in this scenario.

    • @AlexTechie
      @AlexTechie Před 4 lety +3

      @@coreyms Great video, Corey, but i have a question:
      @ 3:24 I understand completely that no new memory needed to be allocated for the list when you modified it, but if you print out the memory address of a[0] before and after changing the value, both values use a different memory address. If the values inside the list require a memory address, doesn't that negated the performance improvements of using a list?

    • @timurdothamzin
      @timurdothamzin Před 4 lety +3

      ​@@AlexTechie , that's what I thought about, too. I guess the performance gain comes from the fact that less data is being copied each time you make and assignment. If you store the result of the operation in one string, the whole result is being copied each time, which has a snowballing effect and slowing down every next operation, which is not the case if you mutate list items instead.

  • @Fat1Dada
    @Fat1Dada Před 8 lety +4

    +1 for clarity and choice of example with the String class at the beggining :) thank you!

  • @alishashrestha7967
    @alishashrestha7967 Před 4 lety +2

    By far the best explanation of immutability for beginners. Thanks!

  • @TheLollercaster
    @TheLollercaster Před 5 lety +2

    thanks for the video, I wanted to understands mutable vs immutable in terms of JavaScript, and your example really helped me out to understand it

  • @YeGaogaosanyong
    @YeGaogaosanyong Před 4 lety +1

    The difference between mutable and immutable objects is very nicely explained in the first half of the video. You are absolutely correct that an application which keeps appending value to an immutable object runs slow as it constantly copies the existing value to a new memory space. However, there is no guarantee that by changing it to a mutable object the application will run fast. Using list, it is indeed the case as list in Python is essentially a variable-sized array which has extra spaces to add new elements. So its operation to append is "amortized" O(1). But if one uses numpy array, then it is essentially the same as using string which copies the existing elements over to a new memory location whenever new elements are appended (i.e. O(N) operation).

  • @mrsajjad30
    @mrsajjad30 Před 3 lety

    Thank you for compiling such a beautiful example for explaining the topic.

  • @cd-stephen
    @cd-stephen Před 6 lety +1

    Corey - Your explanations are amazing,

  • @LopogaX
    @LopogaX Před 7 lety

    This playlist is what I was looking for, good tutorial

  • @potatobot2802
    @potatobot2802 Před 9 měsíci

    Thank you so much for your generous time and effort!

  • @MarcusLucasOficial
    @MarcusLucasOficial Před 4 lety +1

    This is the greatest explanation on this top! Can you give more examples when using mutable and immutable variables are good or bad when processing large amounts of data?

  • @self.medicate
    @self.medicate Před 3 lety

    Thanks so much for explaining why its important to know which objects are mutable and which are not.

  • @farrukhafzaal940
    @farrukhafzaal940 Před 2 lety

    Thank you @Corey, this is a wonderful explanation

  • @RC-bl2pm
    @RC-bl2pm Před 6 lety +1

    Corey you really push the fog out. Thanks very much.

  • @william.darrigo
    @william.darrigo Před rokem

    You explained this so clearly. Thanks 😊

  • @bhaskarkush.2932
    @bhaskarkush.2932 Před rokem

    Great explanation buddy .... Keep up the great work

  • @pinkfloyd089
    @pinkfloyd089 Před 4 lety +1

    best video to explain the concept . Thank you

  • @abhilashm4911
    @abhilashm4911 Před 6 lety +1

    thank you very much Corey , u explain very clearly

  • @kollivenkatamadhukar5059

    Great Explination 5 articles = 1 Video

  • @Ryan-vn7de
    @Ryan-vn7de Před 6 lety

    Awesome explanation, thanks!

  • @nallilley3863
    @nallilley3863 Před 4 lety +1

    Super helpful. Thanks. UK CS teacher.

  • @basselkordy8223
    @basselkordy8223 Před 2 lety

    Very informative, Thanks!

  • @mitchellvandoorn2625
    @mitchellvandoorn2625 Před 4 lety +1

    This was clear, thanks!

  • @mohamedbilal5634
    @mohamedbilal5634 Před 6 lety

    Thanks for the great explanation

  • @ZeryusXD
    @ZeryusXD Před 3 lety

    Excellent explanation thanks!

  • @deanbitter2718
    @deanbitter2718 Před rokem

    your explanation was Awesome.

  • @bobsonclimber
    @bobsonclimber Před 2 lety

    Excellent explanation..thank you

  • @viktornikolov827
    @viktornikolov827 Před 2 lety

    A very helpful video, thank you!

  • @rohithanda6669
    @rohithanda6669 Před 4 lety +1

    Very well explained...!

  • @AbhishekKumar-qr5ql
    @AbhishekKumar-qr5ql Před 3 lety +1

    Best explanation !!

  • @radhakrishnavarukuti1601
    @radhakrishnavarukuti1601 Před 5 lety +1

    great explanation!!

  • @qguk
    @qguk Před 2 lety

    Thank you so much this was briliantly clear

  • @malus08
    @malus08 Před 2 lety

    Great video!!

  • @evgenygoldin5024
    @evgenygoldin5024 Před 8 lety

    Gold! Thank you a lot!

  •  Před 7 lety

    Thank you very much, you're very clear

  • @Michael17000
    @Michael17000 Před 2 lety

    Many thanks

  • @think.force-anil
    @think.force-anil Před 6 lety +30

    Hi Corey, thanks for this video. Well the String and StringBuffer example was comprehensible. You made it very clear that having to concatenate 1000's of string would take a performance hit and it would be highly memory inefficient to do that. But you forgot to state what would be the memory efficient way to approach this problem. What would be the StringBuffer/StringBuilder equivalent Java solution in Python?

    • @anon-sl4vp
      @anon-sl4vp Před 5 lety +3

      Id guess you would use a list and append to the list :)

    • @anon-sl4vp
      @anon-sl4vp Před 5 lety +5

      altho i dont think it matter's too much as garbage collection picks it up???
      import gc
      a = 'hello'
      a += 'psds'
      a += 'kok'
      a += 'no way'
      refs = gc.get_referrers(a)
      print(len(refs))
      #1
      1 reference to `a` object,

    • @nandhakumar2705
      @nandhakumar2705 Před 4 lety +3

      We can use join instead,
      ",".join(employees)

    • @Christopher-sl7cm
      @Christopher-sl7cm Před 2 lety

      @@anon-sl4vp Relying on GC to clean up poor memory management is not a good practice. This is one of the reasons against using Java. New object allocation doesn't just waste memory, it takes a lot of unnecessary time to do so, especially if it's on the heap.

    • @thanitsakleuangsupornpong2449
      @thanitsakleuangsupornpong2449 Před rokem

      @@Christopher-sl7cm Yeah GC can takes lots of time especially if there are lots of object on the heap, and should use it often like that. But it's not a bad practice in some scenario especially in a game industry where we run Garbage Collector on the loading time, for example, when changing to a new level. Also Garbage Collector only deallocates unused heap memory anyways unlike stack which get deallocated as soon as the variable it refers to goes out of scope.

  • @rapirapir1544
    @rapirapir1544 Před 5 lety

    Why have I not found your videos up until now

  • @musicfan2000
    @musicfan2000 Před 3 lety

    thank you, king

  • @fosatech
    @fosatech Před 6 lety

    Thanks! Subscribed

  • @mritunjaykumar8684
    @mritunjaykumar8684 Před 6 lety

    Your last minute lines just cleared all things. But, how can I determine whether the method I am creating or functions I am using is mutable or immutable?

  • @shixianli1367
    @shixianli1367 Před 4 lety +1

    great video

  • @mickmack9360
    @mickmack9360 Před 6 lety +5

    Great Videos, thank you!! One question: The different addresses are the addresses to which output pointed in the past. However, after each concatenation the old object gets garbage collected. So where is the problem? All the time, there is just one object, that moves from one location in memory to another, letting the old objects be destroyed...

    • @petrolbears
      @petrolbears Před 5 lety

      Exactly, I thought so too... Can someone with more knowledge on this clarify it? thanks.

    • @user-xc5xf8gp8n
      @user-xc5xf8gp8n Před 4 lety +1

      I think Corey is saying that the process you mentioned slows down the speed of the program, since creating a new memory address and garbage collecting the old one is also a work for the CPU. And when that is performed millions amounts of times in a loop, it can severely deprecate the program speed.

    • @chengguanpropertysg9140
      @chengguanpropertysg9140 Před 4 lety +2

      The problem is with the copy operation. Imagine each iteration it copies 10 bytes, the in the 1000th iteration, it would be copying 1010 bytes... if u use a mutable list, then u will consistently copying 10 bytes into the list...

  • @Limpuls
    @Limpuls Před 7 lety

    Thanks for this great explanation. I have a question. Can perfomance issues for immutable objects be solved by using recursions instead of loop iterations? I ask because functional languages use immutable data structures and a lot of those languages do not have loops originally in the language.

    • @jg9193
      @jg9193 Před 6 lety

      Python lacks support for tail call optimization, so using recursion in python is actually more expensive in terms of memory than using a for loop

  • @EminoMeneko
    @EminoMeneko Před rokem

    There is string buffer in Java too I think but also StringBuilder I always use.
    Is it that much of an issue? Is there no garbage collection in Python ?
    Good to see you have a series of technical terms to clarify.

  • @user-kc5wn1ti3b
    @user-kc5wn1ti3b Před 4 lety

    When'd the garbage collector release the previous addresses when concatenating the string(the example with the html list)?

  • @jakubknitter2679
    @jakubknitter2679 Před 7 lety

    What about StringBuilder? Is it not better than StringBuffer class considering performance?

  • @Epistemer
    @Epistemer Před 5 lety +1

    thank you :)

  • @mountainking212
    @mountainking212 Před 6 lety +4

    Hi Corey, thanks for your video. If strings are immutable, how is it possible that you can append a new string to the original one? This is in reference to the last example in your video.

    • @coreyms
      @coreyms  Před 6 lety +6

      This is because it's actually creating a new object in the background. So when you append a new string to the original, it creates a new object with the string appended to the original. If strings were mutable, like lists, then it wouldn't need to create a new object to do this.

  • @bloodbath8804
    @bloodbath8804 Před 3 lety

    thank you very much very very much

  • @pavelooo2289
    @pavelooo2289 Před 4 lety

    Thanks for clearing the concepts. -the 1000th liker.

  • @cliffordmathew1036
    @cliffordmathew1036 Před 3 lety

    Thanks

  • @xonted5929
    @xonted5929 Před 6 lety

    thank you

  • @swadhikarc7858
    @swadhikarc7858 Před 7 lety

    Can't explain more simpler than corey does

  • @koferperk
    @koferperk Před 2 lety

    thanks!

  •  Před 6 lety

    Is there a book where I can find these programming terms?

  • @academichelp8738
    @academichelp8738 Před 6 lety

    when i create this array estsim=np.zeros(9000,9000,2), dtype=np.int), again in python, it gives Memmory error. Can you help me out please.

  • @ankitjhunjhunwala9895
    @ankitjhunjhunwala9895 Před 3 lety +1

    Adding one more point, immutability makes the data thread safe.

  • @jamespretlow3028
    @jamespretlow3028 Před 8 lety +3

    I hope you have some classes on Udemy. If so, let me know and I will sign up.

  • @yogeshbaviskar2292
    @yogeshbaviskar2292 Před 7 lety

    In the last section, you have used a list containing multiple strings. You showed that the various strings are stored at different addresses. As List is mutable, so is it like if I change the value in one of the string in the list it will modify it at the same address ?

    • @coreyms
      @coreyms  Před 7 lety +1

      The list would be modified and keep the same address. However, the address of the value in the list you changed would have a different address. For example:
      >>> l = ['a', 'b', 'c']
      >>> id(l)
      4387756040
      >>> id(l[0])
      4386013736
      >>> l[0] = 'd'
      >>> id(l)
      4387756040
      >>> id(l[0])
      4385877720
      I hope that makes sense

    • @ReggaeUnicorn
      @ReggaeUnicorn Před 7 lety

      Looks like you cut out part of your solution, could you repost it?

  • @love_radiation6408
    @love_radiation6408 Před 3 lety

    Can you explain dynamically typed programming

  • @tcao1k
    @tcao1k Před 6 lety

    Hi Corey,
    how is using remove an element in a list vs a string that could make more sense in immutable with mutable ? since, it is possible to replace a letter "o" or "a" or "A" in string but it's ID still point to the same memory location.
    >>> str2 = " hello "
    >>> str2.replace("o","a")
    ' hella '
    >>> print id(str2)
    41547264
    >>> str2.replace("o","A")
    ' hellA '
    >>> print id(str2)
    41547264
    >>> str2.replace(" ","A")
    'AhelloA'
    >>> print id(str2)
    41547264
    #--- list--#
    >>> lst
    [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 'a', 2]
    >>> print id(lst)
    41465776
    >>> lst.pop(2)
    4
    >>> print id(lst)
    41465776
    >>>

    • @coreyms
      @coreyms  Před 6 lety +2

      Hey there. string.replace actually returns a new string and does not modify the original str2 variable you have set. So if you were to print str2 after doing the replace, it would still be equal to the original 'hello' string, hence why it's the same id. If you want to capture the replaces string then you need to set a new variable. Something like:
      replaced_str2 = str2.replace('o', 'a')

    • @tcao1k
      @tcao1k Před 6 lety

      Thanks Corey.. i got it...
      >>> print id(str1)
      61866752
      >>> print "str1: {} and id {}". format(str1,id(str1))
      str1: hello and id 61866752
      >>> re_str1 = str1.replace("o","y")
      >>> print "re_str1: {} and id {}". format(re_str1,id(re_str1))
      re_str1: helly and id 50813888
      >>> print "str1: {} and id {}". format(str1,id(str1))
      str1: hello and id 61866752

    • @thirumalaivasan6745
      @thirumalaivasan6745 Před 5 lety

      Can anybody explain me how did he commented multiple lines of codes using shortcut key? as a windows user?

    • @Balajionceagain
      @Balajionceagain Před 3 lety

      @@thirumalaivasan6745 cntrl + \

    • @thirumalaivasan6745
      @thirumalaivasan6745 Před 3 lety

      @@Balajionceagain Gotcha bro, that's like ctrl + \ is like uncomment a line.
      But ctrl + / is comment! thanks i gotcha! long live bro!

  • @deadlock107
    @deadlock107 Před 5 lety +1

    I don't get it totally. So when I make a variable like x="arbitrary string", then change to x="another string" , then the first one still remains in the memory or the memory space disengage?

    • @petrolbears
      @petrolbears Před 5 lety

      My question exactly. I thought that the memory will be freed up, as the variable keeps being overwritten? So it's the constant overwriting that makes the program inefficient, not the accumulating amount of memory being claimed?

    • @pr02640
      @pr02640 Před 3 lety

      @@petrolbears but if memory will be freed up, how can we see the two addresses in the exmaple? just a question

  • @babelwrap
    @babelwrap Před 6 lety +1

    If you did "a=[6,2,3,4,5]" the address would change, the same way a string would. I believe strings being placed in a different address is not a characteristic of their immutability. Please clarify.

    • @coreyms
      @coreyms  Před 6 lety +3

      The point is that you can change a single value of a mutable data type and it won't change its memory address, but you can't change a single value of an immutable type. It will throw an error.

  • @anwarsosko5963
    @anwarsosko5963 Před 2 lety

    You're amazing

  • @pashnyovv
    @pashnyovv Před 3 lety

    and I didn't get the answer what I can use in python instead of str (like StringBuilder in java) ?

  • @insertoyouroemail
    @insertoyouroemail Před 5 lety

    Optimization is not only relevant in terms of performance but also in terms of maintainability, reliability, predictability and readability.

  • @arkb9
    @arkb9 Před 4 lety

    What’s happening in the employee example? I mean how could I make the list mutable?

    • @nandhakumar2705
      @nandhakumar2705 Před 4 lety +1

      List is already mutable,
      In this case you can use join,
      ",".join(employees)

  • @peacemekka
    @peacemekka Před 3 lety

    nice.

  • @ShahzaibKhan-li8wi
    @ShahzaibKhan-li8wi Před 5 lety

    i'm trying to print address of variable but not printing

  • @user-xc5xf8gp8n
    @user-xc5xf8gp8n Před 4 lety +6

    Summary:
    1. 'Mutable' means that an object can be modified, while 'immutable means it can't.
    2. We can check whether a data is mutable or not by printing out the id(memory address) of an object after performing an modification to the data type.
    3. Example#1. Strings are immutable in Python. But we can still reassign a whole new string value oto a variable that holds a string. However, it is not possible to modify a substring while keeping the memory address the same.
    4. Example#2. Lists are mutable in Python. We can change one item of the list while keeping the memory address of the entire list the same.
    5. Why should we know this concept? There are 2 reasons
    5-1 We can avoid and fix errors caused by modifying an immutable data type.
    5-2 We can speed up our programs. Memories are being shifted when performing operations on immutable objects means that it is going to take a lot more amount of time, and making our program slower. By avoiding operations on immutable data and thus the memory shift, we can improve our program speed.

  • @rachelwinchell4681
    @rachelwinchell4681 Před 4 lety

    I'm getting a syntax error when I go to print a. wants me to add (). please advise

    • @rootytuners
      @rootytuners Před 4 lety +1

      The example in the video is Python 2 syntax. It’s possible you are running it in a Python 3 environment. In Python 3, it would be, print(“a”).

  • @thirumalaivasan6745
    @thirumalaivasan6745 Před 5 lety

    Can anybody explain me how did he commented multiple lines of codes using shortcut key? as a windows user? 3:07

  • @andytheodorko9874
    @andytheodorko9874 Před 4 lety

    Why not make strings mutable?
    What can I use in C# to make the string mutable? What about char[], is this mutable? Any consequences of not using string but using char[]?

    • @charkaouiomar1995
      @charkaouiomar1995 Před 4 lety

      www.c-sharpcorner.com/article/mutable-and-immutable-class-in-c-sharp/#:~:text=Mutable%20and%20immutable%20are%20English,and%20%22cannot%20change%22%20respectively.&text=When%20we%20change%20the%20value,is%20stored%20in%20new%20memory.

  • @JadeJuno
    @JadeJuno Před 2 lety

    My main question about this mutable and immutable stuff, is why would you want to have an immutable value over a mutable one?-

  • @srinidhiskanda754
    @srinidhiskanda754 Před 8 lety +1

    tanx. if string is immutable and has performance issue than why did string is made immutable

    • @coreyms
      @coreyms  Před 8 lety +4

      Hi there, great question. There are a lot of pros and cons to both mutable and immutable objects. I read a great answer to this question on one of the stackexchange sites, so I believe instead of copying their answer word-for-word, I'll just provide the link. This should answer some of your questions:
      programmers.stackexchange.com/questions/151733/if-immutable-objects-are-good-why-do-people-keep-creating-mutable-objects

    • @houssemzaier
      @houssemzaier Před 7 lety

      String in java (like many other classes) gives an immutable object, this may have some performance issue but the advantage of this kind of object is that they are :
      ThreadSafe
      They have fast retrieving from memory,
      easiest for values copy

  • @nicolasdupere
    @nicolasdupere Před 6 lety

    You are so good to explain... who are the 2 morons who didn't get it! ;)

  • @user-qn5by5iv7u
    @user-qn5by5iv7u Před rokem

    2022

  • @ayushyadav1010
    @ayushyadav1010 Před 3 lety

    Is

  • @soham19902008
    @soham19902008 Před 4 lety

    Dear Corey,
    May I please have your mail id, so that I may ask a few things.
    Thank You

    • @coreyms
      @coreyms  Před 4 lety +1

      CoreyMSchafer@gmail.com
      I get many questions per day so I’ll do my best to answer, but no promises.

  • @colinmaharaj
    @colinmaharaj Před 2 lety

    Immutable mean, don't use that language.

  • @justgivemethetruth
    @justgivemethetruth Před 7 lety

    Why do you always use the word "whenever" when the word "when" would work just fine, and even be more appropriate in about half your cases? This is one of those mindless things people from the South do just to sound Southern, huh?

    • @coreyms
      @coreyms  Před 7 lety +2

      Just how some people talk.

  • @alinapostol2230
    @alinapostol2230 Před 3 lety

    Great explanation, thanks!

  • @rapirapir1544
    @rapirapir1544 Před 5 lety

    Why have I not found your videos up until now