Python Membership Operators
In this page:
item in collection
item not in collection
Membership Operators क्या हैं?
Membership operators जाँचते हैं कि कोई value list, tuple, string, set या dictionary जैसे container के अंदर मौजूद है या नहीं, और हाथ से loop चलाए बिना सादा True या False लौटाते हैं।
ये लगभग अंग्रेज़ी की तरह पढ़े जाते हैं, जो एक कारण है कि membership जाँचने वाला Python code इतना संक्षिप्त और पठनीय होता है।
उदाहरण: What Are Membership Operators?
fruits = ["apple", "banana"]
print("apple" in fruits)
in और not in
in operator True लौटाता है अगर बाईं ओर का value दाईं ओर के container में मिल जाए, और not in उसका ठीक उल्टा है।
दोनों हर built-in sequence और collection type पर काम करते हैं, जो इन्हें भाषा के सबसे व्यापक रूप से पुन: उपयोग होने वाले operators में से एक बनाता है।
उदाहरण: in and not in
fruits = ["apple", "banana"]
print("apple" in fruits) # True, value is present
print("kiwi" not in fruits) # True, value is absent
Strings में Membership
Strings के लिए, in केवल अलग-अलग characters की जाँच करने के बजाय substring खोज करता है, इसलिए cat in concatenate True लौटाता है क्योंकि अक्षरों का वही सटीक क्रम बड़ी string के भीतर मौजूद है।
यह अलग method बुलाए बिना substrings जाँचने का त्वरित तरीका है।
उदाहरण: Membership in Strings
print("cat" in "concatenate")
Dictionaries में Membership
Dictionary पर इस्तेमाल होने पर, in डिफ़ॉल्ट रूप से dictionary की keys के विरुद्ध जाँच करता है, values के नहीं — name in my_dict जाँचता है कि name key है या नहीं, इसलिए किसी value की जाँच के लिए in my_dict.values() साफ़ लिखना पड़ता है।
यह उन शुरुआती लोगों को उलझाता है जो उम्मीद करते हैं कि यह values खोजेगा।
उदाहरण: Membership in Dictionaries
user = {"name": "Alex", "age": 30}
print("name" in user) # checks the dict's keys by default
print("Alex" in user.values()) # must check .values() explicitly for values
in का __contains__ से संबंध
भीतर से, in container का __contains__ method बुलाता है अगर वह परिभाषित हो, इसीलिए custom classes उस dunder method को खुद लागू करके membership testing support कर सकती हैं।
जिन objects में __contains__ नहीं होता, उनके लिए Python हर element पर iterate करके तुलना करने पर लौट आती है।
उदाहरण: How in Connects to __contains__
class MyBox:
def __init__(self, items):
self.items = items
def __contains__(self, item): # lets "in" work on instances of this class
return item in self.items
box = MyBox([1, 2, 3])
print(2 in box) # calls MyBox.__contains__ under the hood
Chapter Quiz — Complete all 16 topics to unlock
0/16 topics done
Complete these topics first:
- Python print()
- Python input()
- Python Format Strings
- Python f-strings
- Python String Formatting
- Python Arithmetic Operators
- Python Relational Operators
- Python Logical Operators
- Python Bitwise Operators
- Python Assignment Operators
- Python Increment & Decrement
- Python Ternary Operator
- Python Operator Precedence
- Python Identity Operators
- Python Membership Operators
- Python Operators