เมื่อต้องการทราบขนาดหน่วยความจำ (bytes) ที่ทัพเพิลใช้ สามารถใช้ sys.getsizeof()
ตัวอย่างโค้ด
import sys
tuple_1 = ("A", 1, "B", 2, "C", 3)
tuple_2 = ("Java", "Lee", "Code", "Mark", "John")
tuple_3 = ((1, "Bill"), (2, "Ant"), (3, "Fox"), (4, "Cheetah"))
print("The first tuple is:")
print(tuple_1)
print("The second tuple is:")
print(tuple_2)
print("The third tuple is:")
print(tuple_3)
print("Size of first tuple is:", sys.getsizeof(tuple_1), "bytes")
print("Size of second tuple is:", sys.getsizeof(tuple_2), "bytes")
print("Size of third tuple is:", sys.getsizeof(tuple_3), "bytes")ผลลัพธ์
The first tuple is: ('A', 1, 'B', 2, 'C', 3)
The second tuple is: ('Java', 'Lee', 'Code', 'Mark', 'John')
The third tuple is: ((1, 'Bill'), (2, 'Ant'), (3, 'Fox'), (4, 'Cheetah'))
Size of first tuple is: 96 bytes
Size of second tuple is: 88 bytes
Size of third tuple is: 80 bytesคำอธิบาย
นำเข้าโมดูล
sysเพื่อใช้getsizeof()สร้างทัพเพิล 3 แบบ: ค่าผสม, สตริง, ทัพเพิลซ้อน
getsizeof()คืนขนาดของออบเจ็กต์ทัพเพิลเอง (ไม่รวมขนาดของออบเจ็กต์ที่อ้างอิงอยู่ภายใน)ขนาดขึ้นอยู่กับจำนวนองค์ประกอบและโครงสร้างภายใน