#Sample Tuplethistuple = ("apple", "banana", "cherry")print(thistuple) #Create Tuple With One Item#To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.thistuple = ("apple",)print(type(thistuple))#NOT a tuplethistuple = ("apple")print(type(thistuple)) #Change Tuple Values#Convert the tuple into a list to be able to change itx = ("apple", "banana", "cherry")y = list(x)y[1] = "kiwi"x = tuple(y)print(x) #Add Itemsthistuple = ("apple", "banana", "cherry")y = list(thistuple)y.append("orange")thistuple = tuple(y)#Another Waythistuple = ("apple", "banana", "cherry")y = ("orange",)thistuple += yprint(thistuple)#Remove Itemsthistuple = ("apple", "banana", "cherry")y = list(thistuple)y.remove("apple")thistuple = tuple(y)#The del keyword can delete the tuple completelythistuple = ("apple", "banana", "cherry")del thistupleprint(thistuple)#Unpack Tuplesfruits = ("apple", "banana", "cherry")(green, yellow, red) = fruitsprint("green = ",green)print("yellow = ",yellow)print('red = ',red)#Using Asterisk*#If the number of variables is less than the number of values, you can add an * to the variable name and the values will be assigned to the variable as a listfruits = ("apple", "banana", "cherry", "strawberry", "raspberry")(green, yellow, *red) = fruitsprint("Approach 1 : ",green)print("Approach 1 : ",yellow)print("Approach 1 : ",red)fruits = ("apple", "mango", "papaya", "pineapple", "cherry")(green, *tropic, red) = fruitsprint("Approach 2 : ",green)print("Approach 2 : ",tropic)print("Approach 2 : ",red)#Countthistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)x = thistuple.count(5)print(x)
No comments:
Post a Comment