Main Content

Python collections - mutable and imutable

Archive - Originally posted on "The Horse's Mouth" - 2006-11-29 17:15:54 - Graham Ellis

Should you use a list or a tuple ... or perhaps a dictionary to store a collection of objects in your Python program? To help you make the decision, think whether you need to be able to modify the collection after you've created it (mutable) or not (immutable), and whether you want it to be indexed in order, or not.
Those two answers should lead to your collection type:
 UnorderedOrdered
MutableDictionary
{ and }
List
[ and ]
Immutablen/aTuple
( and )

If you want an immutable unordered collection (the empty box in my table), use a dictionary. And when you're initially creating the collection, use ( ), [ ] or { } as shown in the table. Always use [ and ] to reference member elements after the initial creation - Python does it like that to render any code you write polymorphic ... i.e. to be common code that will work whatever the collection type.