Python Tuples
Python Tuples
Tuple
Tuples are used to store multiple items in a single
variable.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
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:
thistuple =
("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Tuple Length
To determine how many items a tuple has, use
the len() function:
Example
Example
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Example
A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")
Example
Negative Indexing
Negative indexing means start from the end.
-1 refers to the last item, -2 refers to the second last
item etc.
Example
Output
Cherry
Range of Indexes
You can specify a range of indexes by specifying where
to start and where to end the range.
Example
Output
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to,
but NOT included, "kiwi":
thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "me
lon", "mango")
print(thistuple[:4])
Output
('apple', 'banana', 'cherry', 'orange')
Example
Output
('orange', 'kiwi', 'melon')
Check if Item Exists
To determine if a specified item is present in a tuple
use the in keyword:
Example
output
Yes, 'apple' is in the fruits tuple
Example
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)
Output
("apple", "kiwi", "cherry")
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.
Output
('apple', 'banana', 'cherry', 'orange')
Example
print(thistuple)
Remove Items
Note: You cannot remove items in a tuple.
Example
Example
The del keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because
the tuple no longer exists
Example
Output
apple
banana
cherry
Example
Example
Output
apple
banana
cherry