Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
You cannot add items to a tuple:
thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # This will raise an error
print(thistuple)
To create a tuple with only one item, you have add a comma after the item, unless Python will not recognize the variable as a tuple.
One item tuple, remember the commma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:
The del
keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
To join two or more tuples you can use the +
operator:
Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)