Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
You can loop through the tuple items by using a for
loop.
Iterate through the items and print the values:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
You will learn more about for
loops in our Python For Loops Chapter.
To determine if a specified item is present in a tuple use the in
keyword:
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
To determine how many items a tuple has, use the len()
method:
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))