List Membership Features

How does Python (2.6.4 in particular) define common list membership? I checked a few tests to see what it does:

def main(): obj = fancy_obj(arg='C:\\') needle = (50, obj) haystack = [(50, fancy_obj(arg='C:\\')), (1, obj,), needle] print (1, fancy_obj(arg='C:\\'),) in haystack print needle in haystack if __name__ == '__main__': main() 

What gives:

 False True 

This tells me that Python is probably checking for object references, which makes sense. Is there anything more definitive that I can look at?

+6
python list
source share
3 answers

From the (Unofficial) Python Species Reference :

For list types and tuples, x in y is true if and only if there is an index i such that x == y[i] is true.

So, in your example, if the fancy_obj class saved the arg value in the instance variable and had to implement the __eq__ method, which returned True, if the two fancy_objs compared had the same value for arg , then (1, fancy_obj(arg='C:\\'),) in haystack will be True.

Corresponding page of the link to the standard library: Built-in types , in particular 5.6 Sequence types

+4
source share

Here is the code from Python's SVN:

 static int list_contains(PyListObject *a, PyObject *el) { Py_ssize_t i; int cmp; for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i), Py_EQ); return cmp; } 

so basically it uses == with the object and each object in the list.

+4
source share

Python uses the (equivalent) operator of == . If the fancy_obj class fancy_obj not define __eq__ (or the cruel old __cmp__ , still supported for backward compatibility), then the equality == , "returns" to the is identifier, and this looks like what happens here.

The relevant documents are here , and I quote:

x in s True if s is x, otherwise False

and "equal" means == true.

+3
source share

All Articles