ก่อนนิยาม Tuple Unpacking เราต้องเข้าใจก่อนว่า Tuple คืออะไร
Tuple
ใน Python Tuple ใช้เก็บวัตถุที่ Immutable (เปลี่ยนแปลงไม่ได้) Tuple เป็นลำดับของวัตถุ Python ที่ Immutable ไม่สามารถเปลี่ยนแปลงได้ และใช้วงเล็บปกติ () มันกำหนดค่าด้านขวา (RHS) ให้กับตัวแปรด้านซ้าย (LHS) อีกทางหนึ่งเรียกว่า Unpacking ของ Tuple ค่าต่างๆ ให้กับตัวแปร ในการ Unpacking จำนวนตัวแปรด้านซ้าย (LHS) ต้องเท่ากับจำนวนค่าใน Tuple ที่กำหนด ใน Packing เราใส่ค่าลงใน Tuple ใหม่ ในขณะที่ Unpacking เราแยกค่าเหล่านั้นออกมาเป็นตัวแปรเดี่ยว
ตัวอย่างที่ 1
my_tuple = ("Tutorials Point", 132, "Employees")
# Tuple packing
company_name, employer_count, information = my_tuple # Tuple unpacking
print(company_name)
print(employer_count)
print(information)
ผลลัพธ์
Tutorials Point 132 Employees
ตัวอย่างที่ 2
my_tuple = ("RRS College of Engg and Technology", 6000, "Engineering")
# Tuple packing
college, students, graduates = my_tuple # Tuple unpacking
print(college)
print(students)
print(graduates)
ผลลัพธ์
RRS College of Engg and Technology 6000 Engineering