Python Tuple Methods: Efficient Tuple Operations

thumb_up 1  ·  sell Python tuple methods, Tuple operations in Python, Tuple manipulation with Python methods

Since a tuple in Python is immutable, the tuple class doesn't define methods for adding or removing items. The tuple class defines only two methods.

Sr.No Methods & Description
1

tuple.count(obj)

Returns count of how many times obj occurs in tuple

2 tuple.index(obj)

Returns the lowest index in tuple that obj appears

Finding the Index of a Tuple Item

The index() method of tuple class returns the index of first occurrence of the given item.

Syntax

tuple.index(obj)

Return value

The index() method returns an integer, representing the index of the first occurrence of "obj".

Example

Take a look at the following example −

 
tup1 = (25, 12, 10, -21, 10, 100) print ("Tup1:", tup1) x = tup1.index(10) print ("First index of 10:", x)

It will produce the following output −

Tup1: (25, 12, 10, -21, 10, 100)
First index of 10: 2

Counting Tuple Items

The count() method in tuple class returns the number of times a given object occurs in the tuple.

Syntax

tuple.count(obj)

Return Value

Number of occurrence of the object. The count() method returns an integer.

Example

 
tup1 = (10, 20, 45, 10, 30, 10, 55) print ("Tup1:", tup1) c = tup1.count(10) print ("count of 10:", c)

It will produce the following output −

Tup1: (10, 20, 45, 10, 30, 10, 55)
count of 10: 3

Example

Even if the items in the tuple contain expressions, they will be evaluated to obtain the count.

Tup1 = (10, 20/80, 0.25, 10/40, 30, 10, 55) print ("Tup1:", tup1) c = tup1.count(0.25) print ("count of 10:", c)

It will produce the following output −

Tup1: (10, 0.25, 0.25, 0.25, 30, 10, 55)
count of 10: 3




The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back