Python Tuples
Tuples are used to store multiple items in a single variable. A tuple is a collection which is ordered and unchangeable.
Creating a Tuple
Tuples are written with round brackets.
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Access Tuple Items
You can access tuple items by referring to the index number, inside square brackets:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1]) # Output: banana
Update Tuples
Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created.
However, there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Unpacking a Tuple
When we create a tuple, we normally assign values to it. This is called "packing" a tuple. But, in Python, we are also allowed to extract the values back into variables. This is called "unpacking".
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
Loop Through a Tuple
You can loop through the tuple items by using a for loop.
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
Tuple Methods
Python has two built-in methods that you can use on tuples.
count(): Returns the number of times a specified value occurs in a tuple.index(): Searches the tuple for a specified value and returns the position of where it was found.