List vs. tuple
Both are very similar, but the list of add, delete search, change can be, and in addition to tuples can not change the definition of (add, delete), and use the same list
Tuples can not be changed, that is the tuple element, if the inside of the element has a list, the list of which data can be changed, because for a list of tuples stored inside its address, i.e., the address can not be changed, but by the data inside the memory address can be found in another piece of change
tuple5 = (1,2,3,4,[5,6,7])
tuple5[1][0] = 400
print(tuple5)
tuple[1] = 1 #报错
Access tuple
Format: tuple name [index]
下标可以为负
tuple4 = (1,2,3,4)
print(tuple4[2]) #输出3
print(tuple[-1]) #输出4
n1,n2,n3,n4 = tuple4 #将元组的元素挨个赋值给n1,n2,n3,n4,相当于拆包
Delete tuples
- Delete the entire tuple, rather than inside the tuple data
tuple6 = (1,2,3)
del tuple6 #del可以删除变量
Operation tuple
- Adding
t7 = (1,2,3)
t8 = (4,5,6)
print(t7 + t8)
t9 = t7 + t8
print(t9)
- repeat
t10 = (1,2,3)
print(t10 * 8)
- Determining whether the element inside the tuple
t11 = (1,2,3)
print(3 in t11)
- Taken tuple
Format: Name tuple [start: end] # no header trailer
t12 = = (1,2,3,4,5,6,7,8,9)
print(t12[3:])
print(t12[:5])
print(t12[2:5])
Two-dimensional tuples
t13 = ((1,2,3),(3,4,5),(6,7,8))
print(t13[1][2])
Programmers usually count from 0
The method of tuples
- Only ()
Returns the number of elements in the tuple
t14 = (1,2,3)
print(len(t14))
- max () / min ()
* The maximum / minimum requirements tuple
t15 = (1,2,4,5,6,7)
print(max(t15))
print(min(t15))
- Converted into a tuple list
And the element group to a list of similar, comparable cast
list = [1,2,3]
t = tuple(list)
print(t)
print(list(t)) #元组转列表
- Traversing the tuple
for i in (1,2,3,4):
print(i)
Why do we need a tuple
Ans: security, because tuples can not be changed, the future can place tuple, try to use a tuple