implementation of "in" that returns the object.

Paul McGuire ptmcg at austin.rr._bogus_.com
Sun Oct 22 12:21:06 EDT 2006


"Jorge Vargas" <jorge.vargas at gmail.com> wrote in message 
news:mailman.939.1161527588.11739.python-list at python.org...
> Hi
>
> I need to check if an object is in a list AND keep a reference to the
> object I have done it this way but is there a better one?
>
>>>> def inplusplus(value,listObj):
> ...     for i in listObj:
> ...             if i is value:
> ...                     return value
> ...     return False
> ...
>>>> l = [1,2,3,4]
>>>> print inplusplus(2,l)
> 2
>>>> print inplusplus(9,l)
> False
>>>> print inplusplus(1,l)
> 1
>>>> l.append(0)
>>>> print inplusplus(0,l)
> 0

Just a couple of quick comments:
1. "if i is value" will check for identity, not equality.  Your example with 
small integers relies on a nonportable CPython implementation of using 
cached objects.  Check out this behavior:

>>> def inplusplus(value,listObj):
...   for i in listObj:
...     if i is value:
...       return value
...   return False
...
>>> a = 5
>>> lst = [ 1,3,5,7 ]
>>> inplusplus(5,lst)
5
>>> inplusplus(a,lst)
5
>>> lst.append( 123456789 )
>>> inplusplus( 123456789,lst)
False

Instead of this loopy "is" test, just use "in":

>>> def inplusplus(value,listObj):
...   if value in listObj: return value
...   return False
...
>>> inplusplus( 123456789,lst)
123456789


2.  What happens if "False" is in the list?  How would you know?

-- Paul





More information about the Python-list mailing list