Python tuple methods are built-in methods used to modify the tuples in programs. Python tuple methods are immutable, meaning their content cannot be modified once they are created. The two methods for tuples are the Python Tuple count() and the Python Tuple index().
What are the two methods for tuples?
The two python tuple methods are:
1.Python Tuple count()
This method returns the number of times a specified element repeats itself inside a tuple.Â
For example:
Source Code:
my_vowels11 = ('a', 'e', 'i', 'o', 'i', 'u')
# count element 'i'
count = my_vowels11.count('i')
# print count
print('The count of i is:', count)
# count element 'p'
count = my_vowels11.count('p')
# print count
print('The count of p is:', count)
Output
The count of i is: 2
The count of p is: 0
2. Python Tuple index()
This method is used to return the index value of the specified element.Â
For example:
Source Code:
my_vowels11 = ('a', 'e', 'i', 'o', 'i', 'u')
print('The index of e:', index)
index = my_vowels11.index('i')
print('The index of i:', index)
Output
The index of e: 1
The index of e: 2
What are the different ways of creating tuple?
In python, creating a tuple is possible by adding elements to parenthesis and separating them using a comma.Â
For example:
my_tuples11 = ()
print(my_tuples11)
# Tuple having integers
my_tuples11 = (1, 2, 3)
print(my_tuples11)
# tuple with mixed datatypes
my_tuples11 = (1, "Hello", 3.4)
print(my_tuples11)
# nested tuple
my_tuples11 = ("mini", [3, 8, 4, 6], (1, 2, 3))
print(my_tuples11)
Output
()
(1, 2, 3)
(1, 'Hello', 3.4)
("mini", [3, 8, 4, 6], (1, 2, 3))
Tuples can also be created without using parenthesis, by using the tuple packing technique.Â
Source Code:
my_tuple111 = 30, 24.6, "doggo"
print(my_tuple111)
# tuple unpacking is also possible
a, b, c = my_tuple111
print(a) # 30
print(b) # 24.6
print(c) # doggo
Output
(30, 24.6, 'doggo')
30
24.6
doggo
What are the basic tuple operations?
Tuples respond to the + and * operators in the same way that strings do. Tuples can undergo the concatenation and repetition operations, but the result is a new tuple.
Leave a Reply