fbpx

Python tuple append is tricky as tuple is immutable. There is no inbuild method associated with tuple but Learn some ways to make it possible and append new element to an existing tuple .

python tuple append
python tuple append

Python tuple append method not available!!

We have already learned about inbuilt python tuple methods and observed that there is no direct method ‘append‘ for tuple like we have for list . We also discussed here – Learn Python Tuple : A Quick and complete Guide about python tuple immutability and that is the main reason we don’t have a direct append method for tuple .

Use python list for python tuple append

We know that python list have an inbuilt function ‘append’ . We can convert tuple into list use append method to add an element and then convert that list back to tuple.

# create a tuple first with name tuple_old
tuple_old=(3,5,8,12)
#Convert the tuple into a list using list() method
list_use=list(tuple_old)
# We can now append as many new numbers as we need using append method 
list_use.append(4)
list_use.append(6)
#Convert the list back to tuple
tuple_new=tuple(list_use)
tuple_new

Output = (3, 5, 8, 12, 4, 6)

Use tuple concatenation to append python tuple

If we need to add two element in an existing tuple ,then create a new tuple with that two element and then use concatenation to make the final tuple having two element appended on it .

# First create a tuple named tuple_old
tuple_old=(3,5,8,12)
# You create another tuple named tuple_append  with element which you want to append
tuple_append=(4,6)
#Concatenate tuple_old and tuple_append using + operator. 
tuple_new=tuple_old + tuple_append
# See if you have new element added in a tuple named tuple_new
tuple_new

Output = (3, 5, 8, 12, 4, 6)

Use * operator to unpack tuples and merge

If you have a list ,set or tuple etc and want to store a part of it into a variable then we can use * .

tuple_old=(3,5,8,12)
tuple_append=(4,6)
# If we want to merge tuple_old and tuple_append then using * operation .You can use variable with * as an element of a tuple. when we use *tuple_old as first tuple element of tuple_new that means, it's an variable and all elements of this variable will be the element of tuple named as tuple_new also. 
tuple_new=(*tuple_old,*tuple_append)
tuple_new

Output = (3, 5, 8, 12, 4, 6)

Want to Learn Python from our Expert . Check this out .

Don’t trust us , See if you like learnpython.com

By tecksed

Leave a Reply

Your email address will not be published. Required fields are marked *

×