Tuple ใน Python เป็น Ordered, Immutable Collection สร้างด้วย Parentheses () และ Comma ,
1. สร้าง Tuple
# Multiple items
colors = ("red", "green", "blue")
print(colors) # ('red', 'green', 'blue')
# Single item - ต้องมี Comma!
single = ("red",) # ✅ Tuple
not_tuple = ("red") # ❌ String!
# Empty Tuple
empty = ()
# Tuple Constructor
colors = tuple(["red", "green", "blue"])
2. เข้าถึง Items
colors = ("red", "green", "blue", "yellow", "orange", "white")
# Index (0-based)
colors[0] # 'red'
colors[2] # 'blue'
# Negative Index
colors[-1] # 'white'
colors[-2] # 'orange'
# Slicing [start:stop:step] - คืนค่าเป็น Tuple ด้วย
colors[1:4] # ('green', 'blue', 'yellow')
colors[::2] # ('red', 'blue', 'orange')
colors[::-1] # ('white', 'orange', 'yellow', 'blue', 'green', 'red')
3. วนลูป Tuple
colors = ("red", "green", "blue", "orange")
for color in colors:
print(color)
# With Index
for i, color in enumerate(colors):
print(f"{i}: {color}")
4. Tuple Operations
Concatenation (+)
colors = ("red", "green", "blue")
numbers = (1, 2, 3)
combined = colors + numbers
# ('red', 'green', 'blue', 1, 2, 3)
Repetition (*)
("a", "b") * 3 # ('a', 'b', 'a', 'b', 'a', 'b')
Membership Test
"red" in colors # True
"purple" not in colors # True
Length และ Count
len(colors) # 4
colors.count("red") # 1
colors.index("blue") # 2 (หา Index แรกที่เจอ)
5. Immutability (ไม่สามารถเปลี่ยนแปลงได้)
colors = ("red", "green", "blue")
# colors[0] = "yellow" # ❌ TypeError: 'tuple' object does not support item assignment
# แต่มัน Mutable Object ภายใน Tuple ได้
mixed = ([1, 2], "hello")
mixed[0].append(3) # ✅ List ภายในเปลี่ยนได้
print(mixed) # ([1, 2, 3], 'hello')
6. ลบ Tuple
colors = ("red", "green", "blue")
del colors
# print(colors) # NameError: name 'colors' is not defined
7. Tuple Unpacking (Pattern Matching)
# Basic Unpacking
colors = ("red", "green", "blue")
r, g, b = colors
print(r, g, b) # red green blue
# Extended Unpacking (Python 3+)
numbers = (1, 2, 3, 4, 5)
first, *middle, last = numbers
print(first) # 1
print(middle) # [2, 3, 4] (เป็น List!)
print(last) # 5
# Swap Variables
a, b = 10, 20
a, b = b, a
print(a, b) # 20 10
8. NamedTuple (Readable, Lightweight)
from collections import namedtuple
from typing import NamedTuple
# Classic
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y) # 10 20
# Modern (Python 3.6+) - Type Hints
class Point(NamedTuple):
x: int
y: int
p = Point(10, 20)
print(p.x, p.y) # 10 20
เมื่อไหร่ควรใช้ Tuple แทน List?
| ใช้ Tuple | ใช้ List |
|---|---|
| ข้อมูลไม่ควรเปลี่ยนแปลง (Immutable) | ต้อง Add/Remove/Modify บ่อย |
| เป็น Key ของ Dict / Element ของ Set | ลำดับข้อมูลสำคัญ แต่อาจเปลี่ยน |
| Return Multiple Values จาก Function | ต้องการ Methods: sort, reverse, append |
| Performance Critical (เร็วกว่าเล็กน้อย) | General Purpose |