ออปเปอเรเตอร์สมาชิกใน Python ใช้ทดสอบว่าค่าอยู่ในลำดับข้อมูล (sequence) เช่น สตริง, ลิสต์, หรือ Tuple หรือไม่ มี 2 แบบ:
| ลำดับ | ออปเปอเรเตอร์และคำอธิบาย | ตัวอย่าง |
|---|---|---|
| 1 | in คืน True ถ้าพบตัวแปรในลำดับที่ระบุ มิฉะนั้น False |
x in y คืน 1 ถ้า x เป็นสมาชิกของ y |
| 2 | not in คืน True ถ้าไม่พบตัวแปรในลำดับที่ระบุ มิฉะนั้น False |
x not in y คืน 1 ถ้า x ไม่ใช่สมาชิกของ y |
ตัวอย่างโค้ด
#!/usr/bin/python
a = 10
b = 20
list = [1, 2, 3, 4, 5]
if (a in list):
print "Line 1 - a is available in the given list"
else:
print "Line 1 - a is not available in the given list"
if (b not in list):
print "Line 2 - b is not available in the given list"
else:
print "Line 2 - b is available in the given list"
a = 2
if (a in list):
print "Line 3 - a is available in the given list"
else:
print "Line 3 - a is not available in the given list"
เอาต์พุต
Line 1 - a is not available in the given list Line 2 - b is not available in the given list Line 3 - a is available in the given list