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
>>> tup + (4, )
(1, 2, 3, 4)
t = t + (4,)
like nbv4 said..
but it's make a new tuple.
the meaning is different.
>>> t
(1, 2, 3)
>>> u=t+(4,)
>>> u
(1, 2, 3, 4)
>>> t=u
>>> t
(1, 2, 3, 4)
>>>