Python tuples (type tuple) are the next Python Data Types we will explore.
Python tuples are similar to lists except that they are immutable, which means they can not be changed. Tuples are wrapped in ( )
parentheses. This might look familiar from the dictionary post when we used the dictionary method .items()
. The output of that returns the KvP wrapped in a tuple. Tuples have to be immutable because of keys in dictionaries. If dictionary items were exported, the keys could be modified if not a tuple. Out of the box, this data type provides data integrity.
We are going to use the below example tuple:
my_tup = (1,2,3,4,5,6,7)
As with lists, you can slice and index a tuple to get specific data.
my_tup[:5]
(1, 2, 3, 4, 5)
my_tup[::2]
(1, 3, 5, 7)
my_tup[::-1]
(7, 6, 5, 4, 3, 2, 1)
Tuples have methods and there are only two of them, which can be found here: Tuple Methods. Since they are immutable, you can not change a tuple in place, and there is less you can do with them. The two methods are:
.index()
- This will return the index of the first instance of the object you are looking for
my_tup.index(4)
3
- This will return the index of the first instance of the object you are looking for
.count()
- This counts how many times an element appears in a tuple
- For this, we are going to change it and add more repeating numbers
my_tup = (1, 4, 2, 2, 3, 1, 1, 4, 4, 5, 6, 6, 3, 5, 6)
my_tup.count(1)
3
my_tup.count(6)
3
my_tup.count(2)
2