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 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.
tuples can be created using pair of parentheses by separating items with commas
or using the built-in
# tuples in Python my_tuple = ("a", "b", "c") print(my_tuple) print(type(my_tuple)) my_tuple = tuple(("A", "B", "C")) print(my_tuple) print(type(my_tuple))
('a', 'b', 'c') <class 'tuple'> ('A', 'B', 'C') <class 'tuple'>
Let's learn some of Python tuple methods with code snippets.
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
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