How to add (insert) a new element in a tuple with python ?

Published: February 07, 2019 Protection Status

Tuples are immutable, to add a new element it is necessary to create a new tuple by concatenating multiples tuples or transform it to a list, examples:

Let's consider the following tuple:

>>> t = ('Ben',34,'Lille')

Add an element at the end:

>>> t = t + ('Computer Scientist',)
>>> t
('Ben', 34, 'Lille', 'Computer Scientist')

Note: do not forget the comma ('Computer Scientist',) if not it is a string and not a tuple !

Add an element at the beginning:

>>> t = ('Mr',) + t
>>> t
('Mr', 'Ben', 34, 'Lille', 'Computer Scientist')

Add an element at a given position i:

There are several solution to do that. For example, let's try to add an element at the third position in the tuple:

 >>> t = t[:3] + ('1.90m',) + t[:3]
>>> t
('Mr', 'Ben', 34, '1.90m', 'Mr', 'Ben', 34)

or convert into a list

>>> l = list(t)
>>> l.insert(3,'1.90m')
>>> l
['Mr', 'Ben', 34, '1.90m', 'Lille', 'Computer Scientist']
>>> t = tuple(l)
>>> t
('Mr', 'Ben', 34, '1.90m', 'Lille', 'Computer Scientist')


Links Site
Add Variables to Tuple stackoverflow
Python add item to the tuple stackoverflow