ในการสร้างดัชนีหรือแบ่ง tuple คุณต้องใช้ตัวดำเนินการ [] บน tuple เมื่อสร้างดัชนี tuple หากคุณระบุจำนวนเต็มบวก มันจะดึงดัชนีนั้นจาก tuple นับจากด้านซ้าย ในกรณีของดัชนีติดลบ มันจะดึงดัชนีนั้นจากทูเพิลที่นับจากด้านขวา
ตัวอย่าง
my_tuple = ('a', 'b', 'c', 'd')
print(my_tuple[1])
print(my_tuple[-1]) ผลลัพธ์
สิ่งนี้จะให้ผลลัพธ์ -
b d
ถ้าคุณต้องการได้รับส่วนหนึ่งของทูเพิล ให้ใช้ตัวดำเนินการสไลซ์ [เริ่ม:หยุด:ขั้นตอน].
ตัวอย่าง
my_tuple = ('a', 'b', 'c', 'd')
print(my_tuple[1:]) #Print elements from index 1 to end
print(my_tuple[:2]) #Print elements from start to index 2
print(my_tuple[1:3]) #Print elements from index 1 to index 3
print(my_tuple[::2]) #Print elements from start to end using step sizes of 2 ผลลัพธ์
สิ่งนี้จะให้ผลลัพธ์ -
('b', 'c', 'd')
('a', 'b')
('b', 'c')
('a', 'c')