Python A tuple of is similar to a list , The difference is that the elements of a tuple cannot be modified , You can't add or delete elements , The reason why the above operations cannot be carried out can also be seen from its name ,“ element ” The meaning of has the smallest unit , Immutable .
Tuples use braces ( ), Use square brackets for lists [ ].
How to operate a list , You can refer to my other blog post , Links are as follows :
https://blog.csdn.net/wenhao_ir/article/details/125400072
Tuples are easy to create , You just need to add elements in parentheses , And separate them with commas , Even without brackets .
The sample code is as follows :
tup1 = ('Google', 'CSDN', 1997, 1999)
tup2 = (1, 2, 3, 4, 5)
tup3 = 'a', 'b', 'c', 'd' # You don't need brackets
The operation results are as follows :
Be careful : When a tuple contains only one element , You need to add a comma after the element , Otherwise parentheses will be used as operators .
The sample code is as follows :
tup1 = (50)
tup2 = (50,)
The operation results are as follows :
From the above running results, we can see that ,tup1 Because there is no comma after the element , So it was taken as int type , instead of tuple type .
The sample code is as follows :
tup1 = ('Google', 'CSDN', 1997, 1999)
tup2 = (1, 2, 3, 4, 5)
str1 = tup1[0]
tup3 = tup2[2:5]
The operation results are as follows :
The sample code is as follows :
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
tup3 = tup1 + tup2
The operation results are as follows :
Element values in tuples are not allowed to be deleted , But we can use del Statement to delete the entire tuple .
The sample code is as follows :
tup1 = ('Google', 'CSDN', 1997, 1999)
tup2 = ('abc', 'xyz')
del tup1
The operation results are as follows :
The sample code is as follows :
len1 = len((1, 2, 3))
tup1 = ('Google', 'CSDN', 'tencent', 1997, 1999, 1998)
len2 = len(tup1)
The operation results are as follows :
The sample code is as follows :
tup1 = ('Google', 'CSDN', 'tencent', 1997, 1999, 1998)
tup2 = (4, 5, 6)
tup3 = tup1*2
tup4 = tup2*3
The operation results are as follows :
The sample code is as follows :
tup1 = ('Google', 'CSDN', 'tencent', 1997, 1999, 1998)
bool1 = 'CSDN' in tup1
bool2 = 'zhihu' in tup1
The operation results are as follows :
The sample code is as follows :
tup1 = (456, 700, 200)
max1 = max(tup1)
The operation results are as follows :
tup1 = (456, 700, 200)
min1 = min(tup1)
The operation results are as follows :
The sample code is as follows :
tup1 = ('Google', 'Taobao', 'CSDN', 'Baidu')
list1 = list(tup1)
The operation results are as follows :
A detailed introduction to list related operations , You can refer to another blog post of mine , Links are as follows :
https://blog.csdn.net/wenhao_ir/article/details/125400072
Reference material :
https://blog.csdn.net/wenhao_ir/article/details/125100220