Logo

Personal Ops Runbook

Personal runbook covering infrastructure operations for Cloud, Kubernetes, OpenStack, and Ceph environments. Includes deployment and teardown procedures, node management, cluster monitoring setup, and incident response workflows compiled from day-to-day operational work. Intended strictly for personal reference — configurations and scripts are environment-specific and not guaranteed to work as-is elsewhere.

[Python] Lesson 15 – Tuples


Trong Python, tuples là một kiểu dữ liệu không thay đổi (immutable), nghĩa là sau khi tạo ra, các phần tử bên trong tuple không thể bị thay đổi. Tuples giống như lists, nhưng khác với lists, tuples không thể được sửa đổi, thêm hoặc xóa phần tử. Tuy nhiên, bạn có thể truy cập phần tử bên trong một tuple bằng cách sử dụng index hoặc slicing.

Đây là một đoạn mã Python minh họa việc sử dụng tuples:

# Khởi tạo một tuple
person = ("John", 30, "male")

# Truy xuất các phần tử trong tuple
print("Name:", person[0])
print("Age:", person[1])
print("Gender:", person[2])

# Không thể thay đổi giá trị của các phần tử trong tuple
# person[1] = 32  # Lỗi!

# Khởi tạo tuple từ một list
fruits_list = ["apple", "banana", "cherry"]
fruits_tuple = tuple(fruits_list)

# Duyệt qua các phần tử trong tuple
for fruit in fruits_tuple:
    print(fruit)

# Giải nén tuple
name, age, gender = person
print("Name:", name)
print("Age:", age)
print("Gender:", gender)

# Sử dụng tuple làm key trong dictionary
person_dict = {(name, age): gender}
print(person_dict)

Kết quả khi chạy đoạn mã trên sẽ là:

Name: John
Age: 30
Gender: male
apple
banana
cherry
Name: John
Age: 30
Gender: male
{('John', 30): 'male'}

Ví dụ tiếp theo.

# Khai báo một tuple chứa thông tin của một sinh viên
student = ("John Doe", 25, "Male", "Computer Science")

# Truy cập phần tử bên trong tuple
print(student[0])   # Output: John Doe
print(student[1])   # Output: 25
print(student[2])   # Output: Male
print(student[3])   # Output: Computer Science

# Sử dụng slicing để truy cập một phần của tuple
print(student[:2])   # Output: ("John Doe", 25)

# Cố gắng thay đổi phần tử trong tuple sẽ gây ra lỗi
student[1] = 26   # TypeError: 'tuple' object does not support item assignment

Một ví dụ thực tế của việc sử dụng tuples là khi bạn muốn lưu trữ các giá trị liên quan đến địa chỉ như tên đường, thành phố, quốc gia, mã bưu điện. Vì các giá trị này không được thay đổi thường xuyên, việc sử dụng tuple là lựa chọn tốt hơn so với sử dụng list.