Trong Python, tuple là collection có thứ tự (ordered) và bất biến (immutable). Không thể thêm/xóa item từ tuple.
Tạo tuple dùng ngoặc tròn () và ít nhất một dấu phẩy ( , ).
Tuple hỗ trợ indexing và slicing như list, nhưng kết quả slice cũng là tuple.
Tạo Tuple
colorsTuple = ("red", "green", "blue")
print(colorsTuple) # ('red', 'green', 'blue')
Tuple chỉ có một phần tử
Tuple yêu cầu ít nhất một dấu phẩy. Tạo tuple 1 phần tử phải thêm dấu phẩy sau item:
colorsTuple = ("red",)
Truy cập phần tử Tuple
Truy cập bằng index:
colorsTuple = ("red", "green", "blue")
print(colorsTuple[2]) # blue
Slicing (Cắt phạm vi)
Chỉ định start:end. Kết quả cũng là tuple.
colorsTuple = ("red", "green", "blue", "yellow", "orange", "white")
print(colorsTuple[1:4]) # ('green', 'blue', 'yellow')
Negative Indexing (Chỉ mục âm)
-1 = phần tử cuối, -2 = phần tử倒数第二.
colorsTuple = ("red", "green", "blue", "yellow", "orange", "white")
print(colorsTuple[-2]) # orange
Duyệt qua Tuple
Dùng for loop:
colorsTuple = ("red", "green", "blue", "orange")
for c in colorsTuple:
print(c)
# red, green, blue, orange
Xóa Tuple
Dùng del keyword xóa hoàn toàn:
colorsTuple = ("red", "green", "blue", "orange")
del colorsTuple
print(colorsTuple) # NameError: name 'colorsTuple' is not defined
Độ dài Tuple
Dùng len():
colorsTuple = ("red", "green", "blue", "orange")
print(len(colorsTuple)) # 4
Đếm số lần xuất hiện Item
Dùng count():
colorsTuple = ("red", "green", "blue", "orange", "red")
print(colorsTuple.count("red")) # 2
Nối hai Tuple
Dùng toán tử +:
colorsTuple = ("red", "green", "blue", "orange")
numbersTuple = (1, 2, 3, 4)
numbersAndColors = colorsTuple + numbersTuple
print(numbersAndColors)
# ('red', 'green', 'blue', 'orange', 1, 2, 3, 4)