Monday, September 27, 2010

Insert an item to a tuple in Python

Tuples, like strings, are immutable: it is not possible to assign to the individual items of a tuple ...
[from python doc].

Say you create a tuple t:

>>> t = 1, 2, 3
>>> t
(1, 2, 3)
>>>

Now you need to assign value 4 to the 4th element of the tuple:

>>> t[3] = 4
Traceback (most recent call last):
File "", line 1, in
TypeError: 'tuple' object does not support item assignment

Now you try append like a list:

>>> t.append(4)
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'tuple' object has no attribute 'append'
>>>

No luck yet. So better covert the tuple to a list:

>>> l = list(t)
>>> l
[1, 2, 3]
>>> l.append(4)
>>> l
[1, 2, 3, 4]
>>>

And now convert the list to a tuple:

>>> t = tuple(l)
>>> t
(1, 2, 3, 4)
>>>


Do you know of more ways to do this?

5 comments:

nbv4 said...

>>> tup = (1, 2, 3)
>>> tup + (4, )
(1, 2, 3, 4)

subeen said...

cool. :)

Christian Harms said...

Stake a step back: Why you using tuple If you want to modify?

Tamim Shahriar (Subeen) said...

As far as I can remember, mysql returns result in tuple format and I need to modify it for a special case.

N.C said...

t = 1, 2, 3
t = t + (4,)
like nbv4 said..

but it's make a new tuple.
the meaning is different.