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?