Python | Tuple data type methods

Python Sets with code examples were covered in the previous post. We will gain in-depth information about Python Tuples in this post.

Python Tuples

Python Tuples are immutable sequences, typically used to store collections of heterogeneous data. Tuples are also used for cases where an immutable sequence of homogeneous data is needed.

How to create tuples

tuples can be created using pair of parentheses by separating items with commas{} or using the built-in tuple() function.

# tuples in Python

my_tuple = ("a", "b", "c")

my_tuple = tuple(("A", "B", "C"))
('a', 'b', 'c')
<class 'tuple'>
('A', 'B', 'C')
<class 'tuple'>

Tuple Methods

Let's learn some of Python tuple methods with code snippets.

Python Tuple count() method example

count() method of python tuple returns number of occurrences of a given value.

# tuple count method

my_tuple = ("apple", "banana", "cherry", "apple", "apple")
apple_count = my_tuple.count("apple")

print("number of occurrence of apple in my_tuple:", apple_count)
number of occurrence of apple in my_tuple: 3

Python Tuple index() method example

index() method of python tuple returns the first index of value and raises ValueError if the value is not present.

# tuple index method

my_tuple = ("apple", "banana", "cherry", "apple", "apple")
apple_idx = my_tuple.index("apple")
cherry_idx = my_tuple.index("cherry")

print("Apple Index:", apple_idx)
print("Cherry Index:", cherry_idx)
Apple Index: 0
Cherry Index: 2