Tuple: A tuple is an ordered list. A tuple is very similar to a list, but once a tuple is initialized it cannot be modified
Use parentheses for tuples and square brackets for lists. Tuple creation is as simple as adding elements in parentheses and separating them with commas.
eg: tup = (1, 2,2, 3, 5, 6)
Create empty tuple tup1 =()
When the tuple contains only one element, you need to add a comma after the element tup1 = (1,)
words=(1) words1=('abc') words2 =(1 ,) print (words, type(words)) #Print words and their types print (words1,type(words1)) #Print words1 and their types print (words2,type(words2)) #Print words2 and their types Types of
In the above code, words2 is a tuple
1 <class 'int'> abc <class 'str'> (1,) <class 'tuple'>
Tuples are similar to strings, and the subscript index starts from 0 ( 0 <= i < len(tuple) -1 ), which can be intercepted, combined, viewed, deleted, etc.
Find:
tup = (1, 2, 3, 4, 5, 6, 5, 8 ) print (tup[0]) #first - > 1 print (tup[-2]) #second to last -> 5 print (tup[1:5]) # 2-6th -> (2, 3, 4, 5) print (tup[1:]) # 2nd start -> (2, 3, 4, 5, 6 , 5, 8) print (tup[:-1]) #except the last one -> (1, 2, 3, 4, 5, 6, 5) print (tup.count(5)) #find the number of 5- > 2 print (tup.count(9)) #return 0 if not found -> 0 print (tup.index(5)) #find the subscript of 5, multiple returns to the first -> 4 print (tup.index (50)) #Can't find error -> ValueError: tuple.index(x): x not in tuple
Splice:
tup1 = (12, 34.56) tup2 = ('abc', 'xyz') tup3 = tup1 + tup2 print(tup3) # --> (12, 34.56, 'abc', 'xyz')
delete:
tup = (1, 2, 3, 4, 5, 6, 5, 8 ) del tup print (tup) #After the deletion is successful, printing will report an error, the error message: NameError: name 'tup' is not defined
Built-in functions:
tup1 = (1,2,3,9,4,6) tup2 = (1,0, ' a ' ,0) print (tup1 < tup2) # -> Flase print (len(tup1)) #Count the number of tuple elements. -> 6 print (max(tup1)) #Return the maximum value of the elements in the tuple. -> 9 print (min(tup1)) #Return the minimum value of the elements in the tuple. -> 1 list1 = [1,2,3,4 ] print (tuple(list1)) #Convert the list to a tuple. -> (1, 2, 3, 4) print (tuple( ' abcd ' )) #Convert string to tuple -> ('a', 'b', 'c', 'd')