Does Python have an immutable list?

cammil picture cammil · Jun 21, 2012 · Viewed 65.4k times · Source

Does python have immutable lists?

Suppose I wish to have the functionality of an ordered collection of elements, but which I want to guarantee will not change, how can this be implemented? Lists are ordered but they can be mutated.

Answer

cammil picture cammil · Jun 21, 2012

Yes. It's called a tuple.

So, instead of [1,2] which is a list and which can be mutated, (1,2) is a tuple and cannot.


Further Information:

A one-element tuple cannot be instantiated by writing (1), instead, you need to write (1,). This is because the interpreter has various other uses for parentheses.

You can also do away with parentheses altogether: 1,2 is the same as (1,2)

Note that a tuple is not exactly an immutable list. Click here to read more about the differences between lists and tuples