Mailing List Archive

How to check if a list contains an item
python doesn't have a list.contains() method?


thanks
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to check if a list contains an item [ In reply to ]
online.service.com@gmail.com wrote:
> python doesn't have a list.contains() method?
>

How about the 'in' operator?

In [1]: l1=['aa', 'bb', 'cc']

In [2]: 'aa' in l1
Out[2]: True

In [3]: 'ab' in l1
Out[3]: False

In [4]: 'cc' in l1
Out[4]: True

Will this help?

Esmail


--
http://mail.python.org/mailman/listinfo/python-list
Re: How to check if a list contains an item [ In reply to ]
online.service.com@gmail.com wrote:
> python doesn't have a list.contains() method?
>

How about the 'in' operator?

In [1]: l1=['aa', 'bb', 'cc']

In [2]: 'aa' in l1
Out[2]: True

In [3]: 'ab' in l1
Out[3]: False

In [4]: 'cc' in l1
Out[4]: True

Will this help?

Esmail


--
http://mail.python.org/mailman/listinfo/python-list
Re: How to check if a list contains an item [ In reply to ]
online.service.com@gmail.com wrote:

> python doesn't have a list.contains() method?

It has. It's called list.__contains__() and used indirectly through the 'in'
operator:

>>> "red" in ["red", "green", "blue"]
True
>>> "yellow" in ["red", "green", "blue"]
False

--
http://mail.python.org/mailman/listinfo/python-list
Re: How to check if a list contains an item [ In reply to ]
online.service.com@gmail.com wrote:
> python doesn't have a list.contains() method?
>
It does have a __contains__ method, but that's not called directly. Use
"item in my_list" instead (and the opposite is "item not in my_list").
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to check if a list contains an item [ In reply to ]
online.service.com@gmail.com wrote:
> python doesn't have a list.contains() method?

Because it doesn't need one?

>>> x = [1,2,3,4]
>>> 2 in x
True
>>> 42 in x
False


pedantic side-note, objects can have a __contains__ method which
is used under the covers for "in" testing, so your custom objects
can also test for containment.

-tkc



--
http://mail.python.org/mailman/listinfo/python-list