0

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!

John Coleman
  • 51,337
  • 7
  • 54
  • 119
Valera Maniuk
  • 1,627
  • 3
  • 11
  • 14

2 Answers2

3

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.

John Coleman
  • 51,337
  • 7
  • 54
  • 119
  • Thanks! That is exatly what I tried to learn. I also tried a "subset" exercise, please let me know if there is a better way: subset_of = True while list_1: try: list_2.remove(list_1.pop()) except ValueError: subset_of = False break print(subset_of) – Valera Maniuk Jul 29 '15 at 04:52
  • Sorry, could not figure out how to format code in the comments. – Valera Maniuk Jul 29 '15 at 04:58
1

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!
parity3
  • 643
  • 9
  • 18