mutable sequences

Chris Angelico rosuav at gmail.com
Thu Jun 14 00:04:08 EDT 2018


On Thu, Jun 14, 2018 at 12:56 PM, Sharan Basappa
<sharan.basappa at gmail.com> wrote:
> The term mutable appears quite often in Python.
> Can anyone explain what is meant by mutable and immutable sequences.
>
> For example, Python lists are mutable.
>
> BTW, is the below explanation correct (it is taken from a book I am reading)
>
> Python lists are mutable sequences. They are very similar to tuples, but they
> don't have the restrictions due to immutability.
>
> It says lists are mutable and then says they are immutable???

Lists are indeed mutable. Since they are mutable, they do not have the
restrictions of immutability, which is the state of NOT being mutable.

So what does "mutable" mean? It means the thing can be changed, while
still being itself. It has an identity, and a value, and you can
change the value. If you have a shopping list, it has certain items on
it - you need eggs, milk, bacon, and broccoli - and if you remove
broccoli from the list (seriously, you don't need it), the list is
still that same list.

In contrast, the number 5 is immutable. It is the number 5. It cannot
be any other number and still somehow be "itself". If you add 1 to it,
you now have a different number - you have 6 instead. Numbers are
immutable.

A tuple is like a group of values. For instance, the location (3,4)
can be represented as a tuple. It's immutable in the same way that
numbers are; the position (3,4) is different from the position (6,8)
and it's a completely different "thing".

I'm massively simplifying, but that should give you some idea of what
(im)mutability is.

ChrisA



More information about the Python-list mailing list