Modify a read only tuple

By Christian

Using tuples is very handy because of their flexibility and speed. But there is a drawback. Assigning a single item to a tuple does not work and results in a

 TypeError: object doesn't support item assignment

Appending to the tuple does not work, too. The reason is that tuples are immutable (read only) data structures (http://docs.python.org/lib/typesseq-mutable.html). The trick was provided at http://ada.rg16.asn-wien.ac.at/~python/ how2think/english/chap09.htm: replace the old read-only tuple with the new one where two tuples are concatenated:


>>> tuple = ('a', 'b', 'c', 'd', 'e')
>>> tuple[0]
'a'
>>> tuple[0] = 'A'
TypeError: 'tuple' object does not support item assignment
>>> tuple.append('A')
AttributeError: 'tuple' object has no attribute 'append'
>>> tuple = ('A',) + tuple[1:]
>>> tuple
('A', 'b', 'c', 'd', 'e')

Technorati Tags:

Tags: , , , ,

Leave a Reply