How to add or append a new element to a tuple in python ?

September 09, 2021    /    Viewed: 441    /    Comments: 0    /    Edit


Example of how to add or append a new element to a tuple in python:

Create a tuple

Example of how to create a tuple with 10 elements in python:

t = (0, 1, 1, 2, 3, 5, 8, 13, 21, 34)

to check that the variable is a tuple:

type(t)

should print

tuple

A tuple is data structure in python that can't be modified after being created (e.g. you can't append, add a new element or modify an existing element):

t.append(55)

will print the error message:

AttributeError: 'tuple' object has no attribute 'append'

Append a new element to a tuple in python

To append a new element to a tuple in python, a solution is to first transform the tuple into a list:

l = list(t)

then to append a new element

l.append(89)

and to re-transform into a tuple

t = tuple(l)

then

print(t)
print(type(t))

will print

(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 89)

and

<class 'tuple'>

Insert a new element to a tuple in python

To insert a new element to a tuple we can use the same approach

l = list(t)

then insert a new element

l.insert(10,55)

and to re-transform into a tuple

t = tuple(l)

then

print(t)
print(type(t))

will print here

(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
<class 'tuple'>

Modify an existing element in a tuple in python

Another example of how to modify an existing element in a tuple:

l = list(t)

replace element with index 10:

l[10] = -99

re-transform into a tuple

t = tuple(l)

then

print(type(t))

will print

(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, -99, 89)

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!