Difference between the in keyword and __contains__ in Python -
i wondering if 1 explain difference between "in" keyword of python , contains method
i working sample list , found behavior. when 2 supposed used? there efficiency can achieved if use 1 on other.
>>> my_list = ["a", "b", "c"] >>> my_list.__contains__("a") true >>> "a" in my_list true
from docs:
for list , tuple types, x in y true if , if there exists index such x == y[i] true.
string types, x in y true if , if x substring of y. equivalent test y.find(x) != -1.
for user-defined classes define
__contains__()method, x in y true if , ify.__contains__(x)true.for user-defined classes not define
__contains__()define__iter__(), x in y true if value z x == z produced while iterating on y. if exception raised during iteration, if in raised exception.lastly, old-style iteration protocol tried: if class defines
__getitem__(), x in y true if , if there non-negative integer index such x == y[i], , lower integer indices not raiseindexerrorexception.
Comments
Post a Comment