Access Front and Rear Element ของ Tuple
เมื่อต้องการเข้าถึงเอลีเมนต์ตัวแรก (Front) และตัวสุดท้าย (Rear) ของ Tuple สามารถใช้ Indexing และ Negative Indexing ได้
Tuple เป็น Immutable
Tuple เป็นข้อมูลชนิด Immutable ไม่สามารถเปลี่ยนแปลงค่าโดยเข้าถึง Index ได้ หากลองเปลี่ยนจะเกิด Error เหมาะสำหรับข้อมูลที่ต้องการ Read-only Access
ตัวอย่างโค้ด
my_tuple_1 = (87, 90, 31, 85, 34, 56, 12, 5)
print("The first tuple is :")
print(my_tuple_1)
# Index 0 = ตัวแรก, Index -1 = ตัวสุดท้าย
my_result = (my_tuple_1[0], my_tuple_1[-1])
print("The front and rear elements of the tuple are : ")
print(my_result)
ผลลัพธ์
The first tuple is : (87, 90, 31, 85, 34, 56, 12, 5) The front and rear elements of the tuple are : (87, 5)
คำอธิบาย
- กำหนด Tuple และแสดงผล
- เข้าถึง Element ตัวแรกด้วย
my_tuple_1[0](Index 0) - เข้าถึง Element ตัวสุดท้ายด้วย
my_tuple_1[-1](Negative Index -1) - รวมเป็น Tuple ใหม่เก็บในตัวแปร
- แสดงผลบนคอนโซล
Negative Indexing Explained
my_tuple = (87, 90, 31, 85, 34, 56, 12, 5)
# Index: 0 1 2 3 4 5 6 7
# -Index: -8 -7 -6 -5 -4 -3 -2 -1
print(my_tuple[0]) # 87 (Front)
print(my_tuple[-1]) # 5 (Rear)
print(my_tuple[-2]) # 12 (ตัวก่อนสุดท้าย)
กรณี Tuple ว่าง
empty_tuple = ()
# empty_tuple[0] # IndexError: tuple index out of range
# empty_tuple[-1] # IndexError: tuple index out of range
# ควรเช็คก่อนใช้งาน
if empty_tuple:
front, rear = empty_tuple[0], empty_tuple[-1]
else:
print("Tuple is empty")