Programming Terms: Mutable vs Immutable

Поделиться
HTML-код
  • Опубликовано: 24 ноя 2024

Комментарии • 120

  • @matuagify
    @matuagify 4 года назад +17

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

  • @Avarn388
    @Avarn388 4 года назад +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. :)

  • @YeGaogaosanyong
    @YeGaogaosanyong 5 лет назад +2

    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).

  • @waiitwhaat
    @waiitwhaat 2 года назад +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 5 лет назад +16

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

  • @markrity
    @markrity 8 лет назад +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  8 лет назад +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 5 лет назад +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 5 лет назад +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.

  • @alishashrestha7967
    @alishashrestha7967 4 года назад +2

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

  • @psalt21
    @psalt21 8 лет назад +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.

  • @kollivenkatamadhukar5059
    @kollivenkatamadhukar5059 4 года назад

    Great Explination 5 articles = 1 Video

  • @TheLollercaster
    @TheLollercaster 5 лет назад +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

  • @self.medicate
    @self.medicate 3 года назад

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

  • @mrsajjad30
    @mrsajjad30 4 года назад

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

  • @Fat1Dada
    @Fat1Dada 8 лет назад +4

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

  • @RC-bl2pm
    @RC-bl2pm 7 лет назад +1

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

  • @MarcusLucasOficial
    @MarcusLucasOficial 4 года назад +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?

  • @cd-stephen
    @cd-stephen 7 лет назад +1

    Corey - Your explanations are amazing,

  • @think.force-anil
    @think.force-anil 6 лет назад +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 6 лет назад +3

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

    • @anon-sl4vp
      @anon-sl4vp 6 лет назад +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 4 года назад +3

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

    • @Christopher-sl7cm
      @Christopher-sl7cm 2 года назад

      @@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 Год назад

      @@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.

  • @pinkfloyd089
    @pinkfloyd089 5 лет назад +1

    best video to explain the concept . Thank you

  • @potatobot2802
    @potatobot2802 Год назад

    Thank you so much for your generous time and effort!

  • @nallilley3863
    @nallilley3863 5 лет назад +1

    Super helpful. Thanks. UK CS teacher.

  • @팍준하
    @팍준하 4 года назад +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.

  • @mickmack9360
    @mickmack9360 6 лет назад +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 5 лет назад

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

    • @팍준하
      @팍준하 4 года назад +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 4 года назад +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...

  • @LopogaX
    @LopogaX 7 лет назад

    This playlist is what I was looking for, good tutorial

  • @william.darrigo
    @william.darrigo 2 года назад

    You explained this so clearly. Thanks 😊

  • @deanbitter2718
    @deanbitter2718 2 года назад

    your explanation was Awesome.

  • @AbhishekKumar-qr5ql
    @AbhishekKumar-qr5ql 4 года назад +1

    Best explanation !!

  • @Born2conquer02
    @Born2conquer02 Год назад

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

  • @mitchellvandoorn2625
    @mitchellvandoorn2625 4 года назад +1

    This was clear, thanks!

  • @bobsonclimber
    @bobsonclimber 2 года назад

    Excellent explanation..thank you

  • @rohithanda6669
    @rohithanda6669 5 лет назад +1

    Very well explained...!

  • @farrukhafzaal940
    @farrukhafzaal940 3 года назад

    Thank you @Corey, this is a wonderful explanation

  • @abhilashm4911
    @abhilashm4911 6 лет назад +1

    thank you very much Corey , u explain very clearly

  • @ankitjhunjhunwala9895
    @ankitjhunjhunwala9895 4 года назад +1

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

  • @basselkordy8223
    @basselkordy8223 3 года назад

    Very informative, Thanks!

  • @rapirapir1544
    @rapirapir1544 5 лет назад

    Why have I not found your videos up until now

  • @swadhikarc7858
    @swadhikarc7858 7 лет назад

    Can't explain more simpler than corey does

  • @viktornikolov827
    @viktornikolov827 3 года назад

    A very helpful video, thank you!

  • @EminoMeneko
    @EminoMeneko Год назад

    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.

  • @Ryan-vn7de
    @Ryan-vn7de 6 лет назад

    Awesome explanation, thanks!

  • @mountainking212
    @mountainking212 7 лет назад +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  7 лет назад +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.

  • @musicfan2000
    @musicfan2000 3 года назад

    thank you, king

  • @mohamedbilal5634
    @mohamedbilal5634 6 лет назад

    Thanks for the great explanation

  • @babelwrap
    @babelwrap 6 лет назад +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  6 лет назад +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.

  • @radhakrishnavarukuti1601
    @radhakrishnavarukuti1601 6 лет назад +1

    great explanation!!

  • @MS-pq4il
    @MS-pq4il 3 месяца назад

    You are legend, thank you ❤️

  • @mritunjaykumar8684
    @mritunjaykumar8684 6 лет назад

    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?

  • @Michael17000
    @Michael17000 3 года назад

    Many thanks

  • @GameplayAlchemist
    @GameplayAlchemist 3 года назад

    Thank you so much this was briliantly clear

  • @shixianli1367
    @shixianli1367 4 года назад +1

    great video

  • @malus08
    @malus08 2 года назад

    Great video!!

  • @jamespretlow3028
    @jamespretlow3028 8 лет назад +3

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

  • @pavelooo2289
    @pavelooo2289 4 года назад

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

  •  7 лет назад

    Thank you very much, you're very clear

  • @cliffordmathew1036
    @cliffordmathew1036 3 года назад

    Thanks

  • @evgenygoldin5024
    @evgenygoldin5024 8 лет назад

    Gold! Thank you a lot!

  • @СимеонЧакъров-р4в
    @СимеонЧакъров-р4в 5 лет назад

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

  • @deadlock107
    @deadlock107 5 лет назад +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 5 лет назад

      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 4 года назад

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

  • @love_radiation6408
    @love_radiation6408 3 года назад

    Can you explain dynamically typed programming

  • @bloodbath8804
    @bloodbath8804 4 года назад

    thank you very much very very much

  • @fosatech
    @fosatech 6 лет назад

    Thanks! Subscribed

  • @jakubknitter2679
    @jakubknitter2679 7 лет назад

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

  • @Epistemer
    @Epistemer 6 лет назад +1

    thank you :)

  • @JadeJuno
    @JadeJuno 2 года назад

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

  • @Limpuls
    @Limpuls 7 лет назад

    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 6 лет назад

      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

  • @koferperk
    @koferperk 3 года назад

    thanks!

  • @xonted5929
    @xonted5929 6 лет назад

    thank you

  • @pashnyovv
    @pashnyovv 3 года назад

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

  • @yogeshbaviskar2292
    @yogeshbaviskar2292 7 лет назад

    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  7 лет назад +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 7 лет назад

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

  •  6 лет назад

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

  • @tcao1k
    @tcao1k 7 лет назад

    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  7 лет назад +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 7 лет назад

      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 6 лет назад

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

    • @Balajionceagain
      @Balajionceagain 3 года назад

      @@thirumalaivasan6745 cntrl + \

    • @thirumalaivasan6745
      @thirumalaivasan6745 3 года назад

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

  • @andytheodorko9874
    @andytheodorko9874 4 года назад

    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 4 года назад

      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.

  • @srinidhiskanda754
    @srinidhiskanda754 8 лет назад +1

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

    • @coreyms
      @coreyms  8 лет назад +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

  • @academichelp8738
    @academichelp8738 7 лет назад

    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.

  • @ShahzaibKhan-li8wi
    @ShahzaibKhan-li8wi 5 лет назад

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

  • @arkb9
    @arkb9 4 года назад

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

    • @nandhakumar2705
      @nandhakumar2705 4 года назад +1

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

  • @anwarsosko5963
    @anwarsosko5963 2 года назад

    You're amazing

  • @rachelwinchell4681
    @rachelwinchell4681 4 года назад

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

    • @rootytuners
      @rootytuners 4 года назад

      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”).

  • @peacemekka
    @peacemekka 3 года назад

    nice.

  • @thirumalaivasan6745
    @thirumalaivasan6745 6 лет назад

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

    • @gioxc88
      @gioxc88 5 лет назад +3

      CTRL + /

  • @nicolasdupere
    @nicolasdupere 6 лет назад

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

  • @soham19902008
    @soham19902008 5 лет назад

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

    • @coreyms
      @coreyms  5 лет назад +1

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

  • @АлексейСоков-ь8и
    @АлексейСоков-ь8и 2 года назад

    2022

  • @ayushyadav1010
    @ayushyadav1010 4 года назад

    Is

  • @colinmaharaj
    @colinmaharaj 2 года назад

    Immutable mean, don't use that language.

  • @justgivemethetruth
    @justgivemethetruth 7 лет назад

    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  7 лет назад +2

      Just how some people talk.

  • @ZeryusXD
    @ZeryusXD 3 года назад

    Excellent explanation thanks!

  • @alinapostol2230
    @alinapostol2230 3 года назад

    Great explanation, thanks!

  • @rapirapir1544
    @rapirapir1544 5 лет назад

    Why have I not found your videos up until now