Python มี built-in types พื้นฐาน เช่น int, float, complex, str, bool และ complex built-in types เช่น List, Dict, Tuple, Set
1. List (ลิสต์)
Collection ที่มีลำดับ (ordered) และแก้ไขได้ (mutable) เขียนในวงเล็บปีกกา []
สร้างและเข้าถึง List
my_list = ["car", "bus", "truck"]
print(my_list) # ['car', 'bus', 'truck']
print(my_list[1]) # 'bus' (index เริ่มที่ 0)
เปลี่ยนค่าและลูป
my_list[2] = "van" # เปลี่ยนค่าได้เพราะ mutable
for x in my_list:
print(x)
เมธอดสำคัญของ List
| เมธอด | คำอธิบาย |
|---|---|
append(x) | เพิ่ม x ท้ายลิสต์ |
clear() | ลบสมาชิกทั้งหมด |
copy() | คืนลิสต์ก็อปปี้ (shallow copy) |
count(x) | นับจำนวน x ในลิสต์ |
extend(iterable) | ต่อ iterable เข้าท้ายลิสต์ |
index(x) | หา index แรกของ x |
insert(i, x) | แทรก x ที่ index i |
pop([i]) | ลบและคืนค่าที่ index i (default: ตัวสุดท้าย) |
remove(x) | ลบ x ตัวแรกที่เจอ |
reverse() | กลับลำดับลิสต์ (in-place) |
sort() | เรียงลำดับลิสต์ (in-place) |
2. Dict (ดิกชันนารี)
ชุดข้อมูลแบบไม่มีลำดับ (unordered) ใช้ key เข้าถึงค่า (key-value pairs) เป็น associative array
ตัวอย่าง
student = {"Aadrika": 1, "Adwaita": 9, "Sakya": 11, "Sanj": 22}
print(student["Adwaita"]) # 9
# เพิ่มข้อมูล
student["Krishna"] = 111
print(student)
# {'Aadrika': 1, 'Adwaita': 9, 'Sakya': 11, 'Sanj': 22, 'Krishna': 111}
หมายเหตุ: Python 3.7+ รักษาลำดับการแทรก (insertion order) แต่หลักการคือ dictionary ไม่มีลำดับ
3. Tuple (ทูเพิล)
ชุดข้อมูลที่มีลำดับ (ordered) แต่ ไม่สามารถแก้ไขได้ (immutable) คั่นด้วย comma
ตัวอย่าง
my_tuple = ("car", "bus", "truck")
print(my_tuple[1]) # 'bus'
# my_tuple[2] = "van" # Error! Tuple immutable
for x in my_tuple:
print(x)
เมธอดของ Tuple (มีแค่ 2 ตัว)
| เมธอด | คำอธิบาย |
|---|---|
count(x) | นับจำนวน x ในทูเพิล |
index(x) | หา index แรกของ x |
4. Set (เซต)
ชุดของวัตถุที่ distinct (ไม่ซ้ำกัน) ใช้สำหรับ membership testing ที่เร็ว (O(1))
ตัวอย่าง
A = {"AA", "BB", "CC"}
A.add("DD") # เพิ่มสมาชิก
การดำเนินการเซต (Set Operations)
| การดำเนินการ | เมธอด | โอเปอเรเตอร์ | คำอธิบาย |
|---|---|---|---|
| Union | A.union(B) | A | B | รวมสมาชิกทั้งสองเซต |
| Intersection | A.intersection(B) | A & B | สมาชิกร่วมกัน |
| Difference | A.difference(B) | A - B | อยู่ใน A แต่ไม่อยู่ใน B |
| Symmetric Diff | A.symmetric_difference(B) | A ^ B | อยู่ในอันใดอันหนึ่ง แต่ไม่ใช่ทั้งสอง |
| Subset | A.issubset(B) | A <= B | A เป็น subset ของ B |
| Superset | A.issuperset(B) | A >= B | A เป็น superset ของ B |
ตัวอย่างเพิ่มเติม
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B) # {1, 2, 3, 4, 5, 6}
print(A & B) # {3, 4}
print(A - B) # {1, 2}
print(A ^ B) # {1, 2, 5, 6}
frozenset: เซตที่ immutable สามารถเป็น key ของ dict หรือ element ของ set อื่นได้