0

I'm trying to figure out a cleaner (Pythonic) way to tell whether elements in one list exist in another list, in order but not consecutively. For example, I might have the following lists:

list1 = ["I", "her"]
list2 = ["I", "hate", "her", "sometimes"]
list3 = ["her", "hat", "I", "found"]

I want to return True when comparing list1 to list2, because "I" and "her" exist in list2 in that order, although not consecutively. False would be returned when comparing list1 to list3, because "her" and "I" do not appear in the correct order.

I could write a series of loops and if statements to achieve this, but I was wondering if there was a simpler, built-in way to do it. I have tried using the all() function:

all(i in list2 for i in list1)

This works to find whether all the elements in list1 exist in list2, but does not account for ordering. I've also tried using join:

" ".join(str(i) for i in list1) in list2

This will only return True if the elements from list1 are consecutive in list2.

Any ideas on a simpler way to do this?

A.S.
  • 111
  • 2
  • 7

1 Answers1

-1

Just use the intersection operator for sets:

result = bool(set(list1) & set(list2))

If you want to count only ordered pairs, use zip.

result = any([el1 == el2 for el1, el2 in zip (list1, list2)])
LevB
  • 925
  • 6
  • 10
  • This one doesn't quite work, since it returns True regardless of the ordering of the elements in the second list. For example, it would return True when comparing list1 and list3 also, when it should return False. – A.S. May 14 '20 at 20:01
  • try the second solution I posted for ordered pairs – LevB May 14 '20 at 20:32