Python Tuple Methods¶
count()¶
Use of Tuple count()
#
# vowels tuple
vowels = ('a', 'e', 'i', 'o', 'i', 'u')
# count element 'i'
count = vowels.count('i')
# print count
print('The count of i is:', count)
# count element 'p'
count = vowels.count('p')
# print count
print('The count of p is:', count)
Result 1
Count List and Tuple Elements Inside Tuple
# random tuple
random = ('a', ('a', 'b'), ('a', 'b'), [3, 4])
# count element ('a', 'b')
count = random.count(('a', 'b'))
# print count
print("The count of ('a', 'b') is:", count)
# count element [3, 4]
count = random.count([3, 4])
# print count
print("The count of [3, 4] is:", count)
Result 2
index()¶
Find the index of the element
# vowels tuple
vowels = ('a', 'e', 'i', 'o', 'i', 'u')
# index of 'e' in vowels
index = vowels.index('e')
print('The index of e:', index)
# element 'i' is searched
# index of the first 'i' is returned
index = vowels.index('i')
print('The index of i:', index)
Result 1
Index of the Element not Present in the Tuple
# vowels tuple
vowels = ('a', 'e', 'i', 'o', 'u')
# index of'p' is vowels
index = vowels.index('p')
print('The index of p:', index)
Result 2
Working of index() With Start and End Parameters
# alphabets tuple
alphabets = ('a', 'e', 'i', 'o', 'g', 'l', 'i', 'u')
# index of 'i' in alphabets
index = alphabets.index('e') # 2
print('The index of e:', index)
# 'i' after the 4th index is searched
index = alphabets.index('i', 4) # 6
print('The index of i:', index)
# 'i' between 3rd and 5th index is searched
index = alphabets.index('i', 3, 5) # Error!
print('The index of i:', index)
Result 3