Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I've always found having two completely separate types for the same basic data structure (arrays) to be an awkward design, but not a real problem in practice. (Every language has its warts, Python included, but this isn't an important one.)</p> <blockquote> <p>Why does anyone care if a variable lives at a different place in memory than when it was originally allocated? This whole business of immutability in Python seems to be over emphasized.</p> </blockquote> <p>These are different things. Mutability isn't related to the place it's stored in memory; it means the <em>stuff it points to</em> can't change.</p> <p>Python objects can't change location after they're created, mutable or not. (More accurately, the value of id() can't change--same thing, in practice.) The internal storage of mutable objects can change, but that's a hidden implementation detail.</p> <pre><code>&gt;&gt;&gt; x='hello' &gt;&gt;&gt; id(x) 1234567 &gt;&gt;&gt; x='good bye' &gt;&gt;&gt; id(x) 5432167 </code></pre> <p>This isn't modifying ("mutating") the variable; it's creating a new variable with the same name, and discarding the old one. Compare to a mutating operation:</p> <pre><code>&gt;&gt;&gt; a = [1,2,3] &gt;&gt;&gt; id(a) 3084599212L &gt;&gt;&gt; a[1] = 5 &gt;&gt;&gt; a [1, 5, 3] &gt;&gt;&gt; id(a) 3084599212L </code></pre> <p>As others have pointed out, this allows using arrays as keys to dictionaries, and other data structures that need immutability.</p> <p>Note that keys for dictionaries do not have to be completely immutable. Only the part of it used as a key needs to be immutable; for some uses, this is an important distinction. For example, you could have a class representing a user, which compares equality and a hash by the unique username. You could then hang other mutable data on the class--"user is logged in", etc. Since this doesn't affect equality or the hash, it's possible and perfectly valid to use this as a key in a dictionary. This isn't too commonly needed in Python; I just point it out since several people have claimed that keys need to be "immutable", which is only partially correct. I've used this many times with C++ maps and sets, though.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload