implementation of "in" that returns the object.

Paddy paddy3118 at netscape.net
Mon Oct 23 03:05:37 EDT 2006


Jorge Vargas wrote:
> 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

You mentioned a ist of objects.
The following example will return the actual object matched in the ist
allowing you to later change any mutable object returned and see the
change reflected in the list:

>>> x = [[0], [1], [2]]
>>> y = [1]
>>> def inref(val, lst):
... 	try:
... 		return lst[ lst.index(val) ]
... 	except ValueError:
... 		return False
...
>>> z = inref(y, x)
>>> z
[1]
>>> z[0] = 33
>>> z
[33]
>>> x
[[0], [33], [2]]


Hope this helps - Paddy.




More information about the Python-list mailing list