Operation on Tuples:
'''
Manipulating Tuples:
As tuples are immutable, if we want to add, remove, or change the tuples items, then first we must convert the tuple to a list, then perform operation on that list and convert it back to tuple.
'''
#Example:
countries = ("India", "Italy", "Spain", "Australia")
x = list(countries)
print(x) #output = ['India', 'Italy', 'Spain', 'Australia']
x.append("Russia") #add item
print(x) #output = ['India', 'Italy', 'Spain, 'Australia', 'Russia']
x.pop(3) #remove item
print(x) #output = ['India', 'Italy', 'Spain', 'Russia']
x[2] = "England" #change item
print(x) #output = ['India', 'Italy', 'England', 'Russia']
#We covert the tuple to a list, manipulating the items of the list by using list methods, then convert the list back to a tuple.
#However, we can directly concatenate two tuples without converting them to a list.
#Examaple:
countries1 = ("Pakistan", "Afghanistan", "Bangladesh", "Shrilanka")
countries2 = ("Vietnam", "India", "China")
southEastAsia = countries1 + countries2
print(southEastAsia) #output = ('Pakistan', 'Afghanistan', 'Bangladesh', 'Shrilanka', 'Vietnam', 'India' , 'China')
'''
Tuple Methods:
1.count()
2.index() Method
'''
#count()
#It returns the number of times the given element appears in the tuple.
tup1 = (0, 2, 1, 3, 2, 5, 9, 2, 0, 6, 2, 2)
y = tup1. count(2)
print(y) #output = 5
#indeex () Method
#It returns the first occurrence of the given element from the tuple.
#Example:
y = tup1. index(2)
print(y) #output = 1
#It raises a ValueError if the element is not found in the tuple.
#y = tup1. index(8)
#print(y) #output = ValueError: tuple.index(x): x not in tuple
#Syntax:
#tupple.index(element, start, end)
y = tup1.index(2, 3, 10)
print(y) #output = 4
y = len(countries)
print(y) #output = 4
Comments
Post a Comment