Valera Maniuk
Valera Maniuk

Reputation: 1805

How to check if Iterable_1 in iterable_2

How to check if, lets say, list_1 in list_2 without iterating the list_1? Are there any specific 'pythonic' ways or it's better to stick to:

for i in list_1:
  if i in list_2:

Thank you!

Upvotes: 0

Views: 67

Answers (2)

parity3
parity3

Reputation: 703

Python has some functional support with map and filter which help in avoiding levels of iteration.

For iteration with inner conditions/early returns, the any and all functions are effective.

Also, set operations (intersect, union, difference) can be helpful too. It's probably what I would choose when just seeing if the elements in list 1 are in list 2.

list_1 = [ 2, 3 ]
list_2 = [ 1, 2, 3, 4 ]

print set(list_1) in set(list_2) # True

# a more functional approach, although really only makes sense for more specific complex examples!
import operator,itertools,functools
is_in_list_2 = functools.partial(operator.contains,list_2)
print all(itertools.imap(is_in_list_2,list_1)) # will hopefully not call contains more than it needs to!

Upvotes: 1

John Coleman
John Coleman

Reputation: 52008

You seem to be interested in cases where every element in list_1 is also in list_2. In that case a simple

set(list_1) <= set(list_2)

works.

Of course -- if list_2 is a list of lists and you want to know if list_1 is one of those lists a simple

list_1 in list_2

works.

Alternatively, you could be asking if list_1 is a slice of list_2. Just check

list_1 in (list_2[i:j] for j in range(len(list_2)+1) for i in range(j))

You could also check is list_1 is a sub-multiset of list_2 or if list_1 is an increasing subsequence of list_2. I'll leave those as exercises.

Upvotes: 3

Related Questions