Python basic series-(5) tuples

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

  1. Search by index
  2. 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.
  3. count(), count the number of times a certain data appears in the current tuple.
  4. 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=1020['aa'.'bb','cc'],50,30print(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()

Guess you like

Origin blog.csdn.net/qq_46009608/article/details/115017711