[Tutor] Testing Membership in a Sequence
Don Arnold
darnold02 at sprynet.com
Mon Mar 15 19:01:18 EST 2004
On Mar 15, 2004, at 4:42 PM, Christian Wyglendowski wrote:
> Ok, here is a question that I thought I knew the answer to and even
> vaguely remember discussing somewhere, but now I don't have the
> foggiest
> (and I was unable to bend google to do my bidding).
>
> What is the most pythonic way to test for membership of multiple items
> in a sequence? For example:
>
> x = ['a', 'b', 'c']
>
> <pseudo code>
> is ('v' or 'b') in x
> </pseudo code>
>
> I know I can do it via a loop but I was hoping to learn some nice,
> clear, succinct way of doing this. Am I hoping for too much?
> Christian
> http://www.dowski.com
>
I don't know if it's the most Pythonic way, but I'd use a list
comprehension:
a = (1,2,3,4,5,6,7)
b = [1,3,5,8]
c = [item for item in b if item in a]
if c:
print 'common items:', c
else:
print 'no common items found'
common items: [1, 3, 5]
HTH,
Don
More information about the Tutor
mailing list