Membership of multiple items to a list

Christian Heimes lists at cheimes.de
Sun Feb 1 15:00:55 EST 2009


inkhorn schrieb:
> Dear all,
> 
> I'd like to know how to elegantly check a list for the membership of
> any of its items to another list.  Not caring for elegance, I would
> use the following code:
> 
> blah = [1,2,3]
> yadda = [3,4,5,6]
> 
> blah[0] or blah[1] or blah[2] in yadda
> 
> Please tell me how to change the preceding code into something nicer
> where I don't have to keep extending the line based on the length of
> the first list.

You can and should use Python's set type for membership testing.

>>> blah = set([1,2,3])
>>> yadda = set([3,4,5,6])
>>> blah.issubset(yadda)
False
>>> blah.difference(yadda)
set([1, 2])
>>> blah.symmetric_difference(yadda)
set([1, 2, 4, 5, 6])

Christian




More information about the Python-list mailing list