1

I'm a beginner of python 3. Recently, I found that the variable types of python3 can be divided into changeable variable and unchangeable variable. Number, string and tuple belong to immutable variable, and set, dict and list belong to variable variable variable. I'm curious why there is such a difference? In particular, string and tuple are similar to list. Why can't string and tuple change one element but the whole, list not?

  • One essential reason is that dictionary keys must be immutable, and it would be at the very least inconvenient if you could not use integers and strings as dictionary keys. – BoarGules Jan 23 '21 at 08:38
  • I started writing an answer and it got closed before I finished! The main thing I'd suggest is to separate the notion of, _types_, _constants_ and _mutability_. A variable has a type at a given point in time. In Python, that type can change over time (e.g. `a=1` then `a='Hi'`. Numbers are constants of course. Strings can be thought of as constant too, but _immutable_ is more accurate for how they're managed in Python, and applies to tuples. By comparison, lists and other structures are designed to be _mutable_. – Andrew E Jan 23 '21 at 08:40
  • Technically dictionary keys don't need to be immutable, they need to be *unmutated*. If strings and numbers were mutable, dictionaries could store copies of the keys and not leak references to them (e.g. make defensive copies to yield when iterating over the keys). But this sort of added complexity would be needed in *most* code using strings or numbers, so it makes sense not to require it. – kaya3 Jan 23 '21 at 08:41
  • It makes sense to *add to a list* or *add to a set*. It makes less sense and can lead to bugs if you can *mutate the value of a string or number*, rather than creating a new independent string or number. There’s a difference between holding the value `42`, which you wouldn’t expect to change suddenly, and holding a list of undefined length, which you *would* expect to change. – deceze Jan 23 '21 at 08:48

0 Answers0