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:
Return the item in position 1:
Change Tuple Values
Once a tuple is created, you cannot change its values. Tuples are unchangeable.
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 out 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
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
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|