Python Tuple Methods Tutorial

In this section, we will learn about the methods a tuple object provides and how to use them in Python.

Python Tuple Methods:

Objects of type tuple have a couple of useful methods that allow us to get a different sort of information from the target tuple object.

Python Tuple count() Method

The `count()` method allows us to see how many times a specific element was repeated in a tuple object.

Python Tuple count() Method Syntax:

tuple.count(element)

Python Tuple count() Method Parameter

The method takes one argument and that is the name of the element we want to see how many times it was repeated in the target tuple object.

Python Tuple count() Method Return Value

The return value of this method is an integer declaring the number of times an element was repeated in a tuple object.

Example: using python tuple count() method

tup1 = ("Ellen","Jack", "Omid","Elon", "James","Richard","Jeremy", "Ian","Elon", "Kimberly")

print(tup1.count("Elon"))

Output:

2

Python Tuple index() Method

Using the `index()` method, we can find the index position of the first occurrence of the element we put as the argument of this method in a tuple object.

Tuple index() Method Syntax:

tuple.index(element)

Tuple index() Method Parameter

The method takes one argument and that is the name of an element we want to check the target tuple object for the first occurrence of this method.

Tuple index() Method Return Value

The return value of this method is an integer value where it declares the position of the target element.

Note that we get an exception if the target tuple object did not have such value as part of its elements.

Example: using python tuple index() method

tup1 = ("Ellen","Jack", "Omid","Elon", "James","Richard","Jeremy", "Ian","Elon", "Kimberly")

print(tup1.index("Elon"))

Output:

3
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies