Modify a read only tuple


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 ( The trick was provided at 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]
>>> 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: , , , ,

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: Logo

You are commenting using your 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: