ภาพรวม
ตรวจสอบว่าสตริง (key) อยู่ใน list หรือไม่ ใช้ in operator
ตัวอย่างโค้ด
my_list = [4, 3.0, 'python', 'is', 'fun']
key = 'fun'
print("The list is:", my_list)
print("The key is:", key)
if key in my_list:
print("The key is present in the list")
else:
print("The key is not present in the list")
ผลลัพธ์
The list is: [4, 3.0, 'python', 'is', 'fun']
The key is: fun
The key is present in the list
รายละเอียด
inทำงานกับ list, tuple, set, dict (keys), string- Time complexity: O(n) สำหรับ list, O(1) สำหรับ set/dict
- ใช้
not inสำหรับตรวจสอบไม่มี
ขยาย: หา index และ count
# หา index แรก
if key in my_list:
idx = my_list.index(key)
print(f"Found at index {idx}")
# นับจำนวน
count = my_list.count(key)
print(f"Appears {count} times")
# หา index ทั้งหมด
indices = [i for i, v in enumerate(my_list) if v == key]
Performance Tip
ถ้าค้นหาบ่อย ให้แปลงเป็น set ก่อน: my_set = set(my_list) แล้ว key in my_set (O(1))