Course
Tuple Methods
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
Tuple 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.
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
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.