元組使用括號
tup = (1,2,3)
tup2 = ([1,2],[3,4]) # 元組里的元素可以是數組
tup3 = (1,"a") # 元組的元素可以是不同類型的
tup4 = () # 空元組
元組的方法:
1.元組的長度 len()
tup = (1,2,3) print(len(tup)) # 3
2. 元組相加,合並成一個新的元組
tup = (1,2,3) tup2 = (4,5,6) print(tup + tup2) # (1,2,3,4,5,6)
3.元組和數字相乘
tup = ("哈") print(tup * 4) # 哈哈哈哈
4.判斷某個元素是否在元組中
方法一:
if in
tup = (1,2,3) if 1 in tup: print("在")
方法二:
in
tup = (1,2,3) print(1 in tup) # True
5. 迭代元組
for in
tup = (1,2,3) for item in tup: print(item)