A tuple is an ordered, immutable collection in Python, usually written with parentheses (), like (1, 2, 3). It’s like a list, but you can’t change it once it’s created.
Create a tuple, then loop over it with for.
tuple1 = (1, 2, 3, 4, 5)
for element in tuple1:
print(element)output:
1 2 3 4 5
A tuple can hold mixed types; read elements by index.
# 建立一個 tuple
person = ("Alice", 30, "Engineer")
# 用 index 讀元素
name = person[0]
age = person[1]
print(name) # Alice
print(age) # 30output:
Alice 30
A tuple holds mixed types, and like a list you can read it by index or loop over it.
Unpack a tuple into multiple variables in one go.
person = ("Bob", 25, "Designer")
name, age, job = person # unpacking
print(name) # Bob
print(age) # 25
print(job) # Designeroutput:
Bob 25 Designer
