If you want to store multiple data, and these data cannot be modified, Tuple is the best player!
1. Tuple definition
Use parentheses and separate the data with commas . The data can be of different data types!
If the tuple has only one data, add a comma after the data, otherwise it will be considered unique!
tuple1=(1,2,3)
tuple2=(1,)
tuple3=(1)
# 打印数据类型,前两个是元组,tuple。最后一个是int
2. Tuple operation-only searchable
- Search by index
- index(), find a certain data, if the data exists, return the corresponding subscript, otherwise report an error. The syntax is the same as the index method of lists and strings.
- count(), count the number of times a certain data appears in the current tuple.
- len(), count the number of data in the tuple!
Note:
Direct data modification in the tuple will immediately report an error.
If there is a list in the tuple, modifying the data in the list is supported .
tuple1=(‘aa’,'bb','dd','bb')
print(tuple1[0]) #aa
print(tuple1.index('aa')) #0
print(tuple1.count('bb')) #2
print(len(tuple1))
# tuple1[0]='aaa' 会报错,因为本身没有这个元素
tuple2=(10,20,['aa'.'bb','cc'],50,30)
print(tuple2[2])
tuple2[2][0]='aaaa'
print(tuple2)
to sum up
1. Immutable data type
2. When an element, add a comma
3. Common operations: index(), count(), len()