[Tutor] Testing Membership in a Sequence
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Mon Mar 15 20:17:38 EST 2004
On 15 Mar 2004, Greg Whittier wrote:
> My first reaction was ('v' in x) or ('b' in x). I assume you want this
> where there can be more than two items you want to test for. I cheated
> and used list comprehensions, but it looks pretty nifty albeit
> inefficient.
>
> x = ['a','b','c']
> y = ['v','b']
>
> yisinx = 1 in [j in x for j in y]
Hi everyone,
The Set class in the 'sets' Standard Library module can make short work of
this problem:
###
>>> from sets import Set
>>> Set(['v', 'b']) & Set(['a', 'b', 'c'])
>>> Set(['x', 'y']) & Set(['a', 'b', 'c'])
Set([])
###
We're using the idea of "set intersection" by asking: what elements are
shared between the first and second sets?
We can read more about the Set class here:
http://www.python.org/doc/lib/module-sets.html
Good luck!
More information about the Tutor
mailing list