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?

Comments

Anonymous said…
>>> tup = (1, 2, 3)
>>> tup + (4, )
(1, 2, 3, 4)
wingi said…
Stake a step back: Why you using tuple If you want to modify?
Tamim Shahriar said…
As far as I can remember, mysql returns result in tuple format and I need to modify it for a special case.
minstrel said…
t = 1, 2, 3
t = t + (4,)
like nbv4 said..

but it's make a new tuple.
the meaning is different.
Unknown said…
>>> t=1,2,3
>>> t
(1, 2, 3)
>>> u=t+(4,)
>>> u
(1, 2, 3, 4)
>>> t=u
>>> t
(1, 2, 3, 4)
>>>

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code