English subtitles

← Yello Mutation - Intro to Computer Science

Get Embed Code
7 Languages

Showing Revision 6 created 05/24/2016 by Udacity Robot.

  1. So far I've told you that mutation
  2. modifies the existing object.
  3. But you can't really see the difference from what we've done with strings.
  4. Where we'll really see the difference is when we introduce a new variable.
  5. Let's go back to the example we had before,
  6. and now we're going to add an extra assignment statement,
  7. and we'll introduce a new variable.
  8. Suppose we introduce the variable "q."
  9. And we assign p to q, and that means the value of p,
  10. which is the object that's this list,
  11. is now what q will refer to.
  12. The important thing here is after the assignment,
  13. p and q refer to the same list.
  14. Suppose we did an assignment statement
  15. to modify the value of one of the elements of q.
  16. Well, that will change element 4 of q,
  17. so this is element 4 of q.
  18. It will change that value
  19. to the new exclamation point.
  20. It also changed the value of p.
  21. Even though the assignment statement didn't include p,
  22. the fact that p and q refer to the same object
  23. means that it changed the value of p.
  24. To show you that things are different with strings,
  25. let's try that with a string.
  26. See if you can guess what happens when we try to use assignment
  27. to replace the first letter in the string.
  28. Let's run it to see what happens.
  29. And what we get is an error,
  30. and we get an error because the string is not mutable.
  31. There's no way to change the value of the string,
  32. and the error says there's no way to do assignment in a string,
  33. that that type of object, because it's immutable, does not support assignment.
  34. A key difference between mutable objects and immutable objects
  35. is once an object is mutable,
  36. then we have to worry about other variables that might refer to the same object.
  37. We can change the value of that object,
  38. and it affects not just the variable that we think we changed,
  39. it affects the value of other variables as well.
  40. Let's see an example of that.
  41. I've initialized p to the list containing the strings "Hello."
  42. Now I have an assignment that introduces the new variable q
  43. and assigns p to that variable.
  44. And we'll print out the values of p and q,
  45. and we'll see that both p and q contain the string Hello.
  46. But now let's change the value at position 0.
  47. Now we have an assignment that stores
  48. in the value at position 0 of p the letter y.
  49. This changes the value of p.
  50. What may be more surprising is this also changes the value of q.
  51. Even though we didn't use q in the assignment,
  52. it changed the value of q because q
  53. refers to the same object as p.