Table of Contents
ToggleTuple is one of the fundamental data structures in Python, and it is an immutable sequence. Unlike lists, tuples cannot be modified after creation, making them ideal for representing fixed collections of data. This immutability plays a crucial role in various scenarios where data stability and security are important. A tuple can contain elements of different data types, such as integers, floats, strings, or even other tuples.
The tuple class provides a few methods to analyze the data or elements. These methods allow users to retrieve information about the occurrences of specific items within a tuple and their respective indices. Since tuples are immutable, this class doesn’t define methods for adding or removing items. It defines only two methods, which provide a convenient way to analyze tuple data.
To explore all available methods for tuples, you can utilize the Python dir() function, which lists all properties and functions related to a class. Additionally, the help() function provides detailed documentation for each method. Here’s an example:
print(dir((1, 2)))
print(help((1, 2).index))
The above code snippet provides a complete list of properties and functions related to the tuple class. It also demonstrates how to access detailed documentation for a specific method in your Python environment.
The index() method of the tuple class returns the index of the first occurrence of the given item.
tup1 = (25, 12, 10, -21, 10, 100)
print("Tup1:", tup1)
x = tup1.index(10)
print("First index of 10:", x)
Output: Tup1: (25, 12, 10, -21, 10, 100)
First index of 10: 2
The count() method in the tuple class returns the number of times a given object occurs in the tuple.
tup1 = (10, 20, 45, 10, 30, 10, 55)
print("Tup1:", tup1)
c = tup1.count(10)
print("Count of 10:", c)
Output: Tup1: (10, 20, 45, 10, 30, 10, 55)
Count of 10: 3
