0

I am writing simple classifier based on lemmatization and in essence I need to check if a tuple contains any element of the list. Simple example:

>>> ['dog', 'bone'] in ('dog', 'cat', 'parrot')

returns False while I need it to return True. What is the simplest and elegant way to do that?

ande
  • 73
  • 8
  • 1
    `any(x in b for x in a)`--the dupe should be close enough. If the lists are huge create `set`s and intersect them. – ggorlen Aug 16 '20 at 15:24

1 Answers1

0

Either:

any([val in ('dog', 'cat', 'parrot') for val in ['dog', 'bone']])

For actual usage, don't declare the lists and tuples inside the comprehension, as it will waste resources for no reason, you should:

test_list = ['dog', 'bone']
available_items = ('dog', 'cat', 'parrot')
any([val in available_items for val in test_list])

Another possible solution:

set(['dog', 'bone']).intersection(set(('dog', 'cat', 'parrot'))) # Would return a non empty set if there is an intersection, which translates to true.

# Use case:
if set(['dog', 'bone']).intersection(set(('dog', 'cat', 'parrot'))):
    print('intersection!')
Or Y
  • 2,088
  • 3
  • 16
  • 1
    @ggorlen The inner tuple isn't created multiple times. It's a constant that gets used multiple times. – superb rain Aug 16 '20 at 15:41
  • Yeah, you're right--tuples are immutable but if it was a list, I think it'd be created multiple times. My mistake. Still, `any` should probably take a generator rather than a list to allow early bail, and this post is a clear dupe anyway. – ggorlen Aug 16 '20 at 15:43
  • @ggorlen You'll have to write it as for example `list((...))`, though, even `[...]` gets turned into a tuple constant there. I agree with the generator, of course :-) – superb rain Aug 16 '20 at 15:47
  • Nice to know, thanks. – ggorlen Aug 16 '20 at 16:11