Modify a read only tuple

by

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:

Advertisements

Tags: , , , ,

One Response to “Modify a read only tuple”

  1. ddx Says:

    this is not modification of readonly tuple but creating new tuple…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: