Python Tuple Methods – Python Tutorial

1 year ago Lalit Bhagtani 0

In this tutorial, we will learn about different python tuple methods.

Python Tuple Methods

count() method :

This method is used to count total number of occurrence of x ( passed as an argument ) in a tuple object.

Syntax : < Tuple Object >.count(< Argument >)

Example:

[datacamp_exercise lang=”python” height=”50″ min-height=”50″ max-height=”50″]
[datacamp_pre_exercise_code]

[/datacamp_pre_exercise_code]
[datacamp_sample_code]
# create tuple object and assign it to variable t
t = (‘Jan’,’Feb’,’Mar’,’Jan’)

# calling count() method by passing ‘Jan’ as an argument
count = t.count(‘Jan’)

# print the value of variable count
print(count)
[/datacamp_sample_code]
[datacamp_solution]

[/datacamp_solution]
[/datacamp_exercise]

index method :

This method is used to get the index of first occurrence of x ( passed as an argument ) in a tuple object. Here i is a start index and j is a end index, if values of i and j are passed as an argument then first occurrence of x is searched between these two indexes.

Syntax : < Tuple Object >.index(< Argument > [ , i [ ,  j ] ] )

Example:

[datacamp_exercise lang=”python” height=”50″ min-height=”50″ max-height=”50″]
[datacamp_pre_exercise_code]

[/datacamp_pre_exercise_code]
[datacamp_sample_code]
# create tuple object and assign it to variable t
t = (‘Jan’,’Feb’,’Mar’,’Jan’)

# calling index() method by passing ‘Jan’ as an argument
index = t.index(‘Jan’)

# print the value of variable index
print(index)

# calling index() method by passing ‘Jan’ and starting index 1
index = t.index(‘Jan’,1)

# print the value of variable index
print(index)

# calling index() method by passing ‘Jan’, 0 as starting index and 2 as ending index
index = t.index(‘Jan’,0,2)

# print the value of variable index
print(index)
[/datacamp_sample_code]
[datacamp_solution]

[/datacamp_solution]
[/datacamp_exercise]

References :-

  1. Tuple Methods Docs

That’s all for Python Tuple Methods. If you liked it, please share your thoughts in comments section and share it with others too.

Previous