ข้ามไปยังเนื้อหา

Lists และ Tuples

list คือ container หลักของ Python ที่เก็บลำดับของ object ใด ๆ และรองรับการเปลี่ยนแปลงค่าภายใน

fruits = ['apple', 'banana', 'cherry']
fruits.append('date') # เพิ่มที่ท้าย
fruits.insert(1, 'avocado') # แทรกก่อน index 1
fruits.remove('banana') # ลบรายการแรกที่พบ
print(fruits) # ['apple', 'avocado', 'cherry', 'date']
Methodคำอธิบาย
append(x)เพิ่ม x ที่ท้าย
insert(i, x)แทรก x ก่อน index i
remove(x)ลบรายการแรกที่ตรงกับ x
pop(i=-1)ลบและคืนค่า item ที่ index i
sort(key=None, reverse=False)เรียงลำดับใน place
reverse()กลับลำดับใน place
index(x)คืน index ของรายการแรกที่ตรงกับ x
count(x)นับจำนวนรายการที่ตรงกับ x

list.sort() เรียงลำดับใน place และคืนค่า None ส่ง key function เพื่อเรียงตามเกณฑ์ที่กำหนดเอง

numbers = [5, 2, 8, 1, 9, 3]
numbers.sort()
print(numbers) # [1, 2, 3, 5, 8, 9]
words = ['banana', 'apple', 'cherry']
words.sort(key=len)
print(words) # ['apple', 'banana', 'cherry']

ใช้ sorted(iterable) แทน .sort() เมื่อต้องการ list ใหม่โดยไม่แก้ไขต้นฉบับ

tuple คล้าย list แต่ไม่สามารถแก้ไขหลังสร้างแล้ว ใช้ tuple เพื่อแสดง record ที่คงที่ซึ่งตำแหน่งมีความหมาย

rgb = (255, 128, 0) # สีส้ม
point = (3.0, 4.0) # พิกัด 2 มิติ
row = (1, 'Alice', 42) # แถวในฐานข้อมูล

Python อนุญาตให้ unpack tuple (หรือ iterable ใด ๆ) ลงในตัวแปรโดยตรง จำนวนตัวแปรต้องตรงกับความยาว ยกเว้นใช้ * เพื่อรับส่วนที่เหลือ

coords = (10.5, 20.3, 30.1)
x, y, z = coords
print(x, y, z) # 10.5 20.3 30.1
first, *rest = [1, 2, 3, 4, 5]
print(first) # 1
print(rest) # [2, 3, 4, 5]

โดยไม่มีชื่อ field ของ tuple จะถูกเข้าถึงด้วย integer index กำหนด constant เพื่อให้อ่านง่าย:

RGB = (255, 128, 0)
RED = 0
GREEN = 1
BLUE = 2
print(RGB[RED]) # 255
print(RGB[GREEN]) # 128
print(RGB[BLUE]) # 0

สำหรับแนวทางที่สะดวกกว่า ใช้ collections.namedtuple หรือ typing.NamedTuple

# --- list mutation and sorting ---
fruits = ['apple', 'banana', 'cherry']
fruits.append('date')
fruits.insert(1, 'avocado')
print('after insert:', fruits)
fruits.remove('banana')
print('after remove:', fruits)
numbers = [5, 2, 8, 1, 9, 3]
numbers.sort()
print('sorted:', numbers)
words = ['banana', 'apple', 'cherry']
words.sort(key=len)
print('by length:', words)
# --- tuple unpacking ---
coords = (10.5, 20.3, 30.1)
x, y, z = coords
print('unpacked:', x, y, z)
first, *rest = [1, 2, 3, 4, 5]
print('first:', first)
print('rest:', rest)
# --- named fields via index constants ---
RGB = (255, 128, 0)
print('red:', RGB[0], 'green:', RGB[1], 'blue:', RGB[2])
Method ใดที่เพิ่ม element ไปที่ท้าย list?
`list.sort()` คืนค่าอะไร?
ข้อใดเป็น tuple unpacking ที่ถูกต้อง?
ทำไม tuple ถึงใช้เป็น dictionary key ได้แต่ list ไม่ได้?