Tuple
Tuple
Example
Create a Tuple:
Example
Using the tuple() method to make a tuple:
Example
One item tuple, remember the comma:
T = ("oakridge",)
print(type(T))
Output: <class 'tuple'>
#NOT a tuple
T = ("oakridge")
print(type(T))
Output: <class 'str'>
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined
order, and that order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove
items after the tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuples allow duplicate values:
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
Output: 5
Example
Print the second item in the tuple:
Range of Indexes
You can specify a range of indexes by specifying where to start and where to
end the range.
Syntax: T [ start:Stop:Step]
By leaving out the start value, the range will start at the first item:
By leaving out the end value, the range will go on to the end of the list:
By leaving out the step value, the range will go on to every element in
the list:
When specifying a range, the return value will be a new tuple with the specified
items.
Example
Check if "html" is present in the tuple:
But there is a workaround. You can convert the tuple into a list, change the list,
and convert the list back into a tuple.
Example
Convert the tuple into a list to be able to change it:
Add Items
Since tuples are immutable, they do not have a build-in append() method, but
there are other ways to add items to a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, you can
convert it into a list, add your item(s), and convert it back into a tuple.
Example
Convert the tuple into a list, add "xml", and convert it back into a tuple:
2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you
want to add one item, (or many), create a new tuple with the item(s), and add
it to the existing tuple:
Example
Create a new tuple with the value "orange", and add that tuple:
Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can
use the same workaround as we used for changing and adding tuple items:
Example
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
Example
The del keyword can delete the tuple completely:
Output: