Tuple
Tuple
Python Tuples
Tuple is one of 4 built-in data types in Python used to store collections of data,
the other 3 are List, Set, and Dictionary, all with different qualities and usage.
Example
Create a Tuple:
Output
('apple', 'banana', 'cherry')
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.
1
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:
Output
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
2
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Output
Example
One item tuple, remember the comma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Output
<class 'tuple'>
<class 'str'>
Example
String, int and boolean data types:
3
A tuple can contain different data types:
Example
A tuple with strings, integers and boolean values:
type()
From Python's perspective, tuples are defined as objects with the data type
'tuple':
<class 'tuple'>
Example
What is the data type of a tuple?
Output
<class 'tuple'>
4
Tuple Methods
Method Description
index() Searches the tuple for a specified value and returns the position
of where it was found
Python has two built-in methods that you can use on tuples.
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.count(5)
print(x)
Output
5
Python Tuple index() Method
Example
Search for the first occurrence of the value 8, and return its position:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.index(8)
print(x)
Output : 3