Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ความแตกต่างและความคล้ายคลึงระหว่าง Tuple และ List ใน Python

List และ Tuple เรียกว่า Sequence Data Types ของ Python ทั้งคู่เป็น Comma-separated Collection ของ Items ไม่จำเป็นต้องชนิดเดียวกัน

ความคล้ายคลึง (Similarities)

Concatenation, Repetition, Indexing และ Slicing ทำได้ทั้งคู่

# List Operations
L1=[1,2,3]; L2=[4,5,6]
L3=L1+L2        # Concatenation: [1,2,3,4,5,6]
L1*3            # Repetition: [1,2,3,1,2,3,1,2,3]
L3[4]           # Indexing: 5
L3[2:4]         # Slicing: [3,4]

# Tuple Operations
T1=(1,2,3); T2=(4,5,6)
T3=T1+T2        # Concatenation: (1,2,3,4,5,6)
T1*3            # Repetition: (1,2,3,1,2,3,1,2,3)
T3[4]           # Indexing: 5
T3[2:4]         # Slicing: (3,4)

Built-in Functions ร่วมกัน

  • len() - จำนวน Elements
  • max() - ค่าสูงสุด
  • min() - ค่าต่ำสุด

ความแตกต่าง (Differences)

List เป็น Mutable สามารถ Append, Update, Delete Item ได้

L1=[45,32,16,72,24]
L1.append(56)        # [45,32,16,72,24,56]
L1.insert(4,10)      # [45,32,16,72,10,24,56]
L1.remove(16)        # [45,32,72,10,24,56]
L1[2]=100            # Update: [45,32,100,10,24,56]

Tuple เป็น Immutable การแก้ไขจะ Error

T1.append(56)    # AttributeError: 'tuple' object has no attribute 'append'
T1.remove(16)    # AttributeError: 'tuple' object has no attribute 'remove'
T1[2]=100        # TypeError: 'tuple' object does not support item assignment