Python Tuple Methods (original) (raw)

Last Updated : 22 Jul, 2021

Python Tuples is an immutable collection of that are more like lists. Python Provides a couple of methods to work with tuples. In this article, we will discuss these two methods in detail with the help of some examples.

Count() Method

The count() method of Tuple returns the number of times the given element appears in the tuple.

Syntax:

tuple.count(element)

Where the element is the element that is to be counted.

Example 1: Using the Tuple count() method

Python3 `

Creating tuples

Tuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2) Tuple2 = ('python', 'geek', 'python', 'for', 'java', 'python')

count the appearance of 3

res = Tuple1.count(3) print('Count of 3 in Tuple1 is:', res)

count the appearance of python

res = Tuple2.count('python') print('Count of Python in Tuple2 is:', res)

`

Output:

Count of 3 in Tuple1 is: 3 Count of Python in Tuple2 is: 3

Example 2: Counting tuples and lists as elements in Tuples

Python3 `

Creating tuples

Tuple = (0, 1, (2, 3), (2, 3), 1, [3, 2], 'geeks', (0,))

count the appearance of (2, 3)

res = Tuple.count((2, 3)) print('Count of (2, 3) in Tuple is:', res)

count the appearance of [3, 2]

res = Tuple.count([3, 2]) print('Count of [3, 2] in Tuple is:', res)

`

Output:

Count of (2, 3) in Tuple is: 2 Count of [3, 2] in Tuple is: 1

Index() Method

The Index() method returns the first occurrence of the given element from the tuple.

Syntax:

tuple.index(element, start, end)

Parameters:

Note: This method raises a ValueError if the element is not found in the tuple.

Example 1: Using Tuple Index() Method

Python3 `

Creating tuples

Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)

getting the index of 3

res = Tuple.index(3) print('First occurrence of 3 is', res)

getting the index of 3 after 4th

index

res = Tuple.index(3, 4) print('First occurrence of 3 after 4th index is:', res)

`

Output:

First occurrence of 3 is 3 First occurrence of 3 after 4th index is: 5

Example 2: Using Tuple() method when the element is not found

Python3 `

Creating tuples

Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)

getting the index of 3

res = Tuple.index(4)

`

Output:

ValueError: tuple.index(x): x not in tuple

Note: For more information on Python Tuples refer to Python Tuple Tutorial.