A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
Create a Tuple:
Access Tuple Items
You can access tuple items by referring to the index number, inside square brackets:
Print the second item in the tuple:
Negative indexing means beginning from the end,
-1 refers to the last item,
-2 refers to the second last item etc.
Print the last item of the tuple:
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
Return the third, fourth, and fifth item:
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
Range of Negative Indexes
Specify negative indexes if you want to start the search from the end of the tuple:
This example returns the items from index -4 (included) to index -1 (excluded)
Change Tuple Values
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:
y = list(x)
y = "kiwi"
x = tuple(y)
Loop Through a Tuple
You can loop through the tuple items by using a
Iterate through the items and print the values:
for x in thistuple:
You will learn more about
for loops in our Python For Loops Chapter.
Check if Item Exists
To determine if a specified item is present in a tuple use the
Check if "apple" is present in the tuple:
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
To determine how many items a tuple has, use the
Print the number of items in the tuple:
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
You cannot add items to a tuple:
thistuple = "orange" # This will raise an error
Create Tuple With One Item
To create a tuple with only one item, you have to add a comma after the item, unless Python will not recognize the variable as a tuple.
One item tuple, remember the commma:
#NOT a tuple
thistuple = ("apple")
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:
del keyword can delete the tuple
print(thistuple) #this will raise an error because the tuple no longer exists
Join Two Tuples
To join two or more tuples you can use the
Join two tuples:
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
The tuple() Constructor
It is also possible to use the tuple() constructor to make a tuple.
Using the tuple() method to make a tuple:
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|