0

One of the first things I learned about data types in Python is that strings aren't mutable. Can't be changed. However, how you explain this:

a = 'hakuna'
a += ' matata'
print(a)
>>> hakuna matata
Mark
  • 1,385
  • 3
  • 16
  • 29
  • 2
    You aren't changing the string. You're creating a new String then reassigning it back to the same variable. – Carcigenicate Jul 19 '19 at 12:07
  • So I'm not actually changing the string. I'm only changing what the variable `a` is pointing to, right ? Meaning .... the initial value of `hakuna` was garbage-collected at the point when I assigned `a += ' matata'` – Mark Jul 19 '19 at 12:15
  • Yes, basically. And the string isn't necessarily GC'd right away (and probably isn't). It's set up for garbage collection unless other references to the string exist, or the language decides to cache it. But yes, the main point is you're just changing what string `a` is looking at. – Carcigenicate Jul 19 '19 at 12:19

0 Answers0