The sensible way to do this is to use sets. But if you insist on doing it inefficiently by looping, then you need to check that each element of the first list is an element of the second list, and vice versa.
Here are 3 ways to do that check. Notice that (unlike the code in your earlier question) I'm directly iterating over the list elements; there is no need to use list indices for this task in Python.
Firstly, we use an explicit flag ok
to keep track of matches.
#Test if each element of `b` is also an element of `a`
def contains(a, b):
for v in b:
ok = False
for u in a:
if v == u:
ok = True
break
if not ok:
return False
return True
This can be condensed by attaching an else
clause to the inner for
loop:
def contains(a, b):
for v in b:
for u in a:
if v == u:
break
else:
return False
return True
But we can make it even shorter by using the built-in any
function and a generator expression:
def contains(a, b):
for v in b:
if not any(v == u for u in a):
return False
return True
Note that any(v == u for u in a)
will stop testing as soon as it finds a u
that matches v
.
Now for the full matching test. This code works on Python 2 or Python 3.
from __future__ import print_function
def contains(a, b):
for v in b:
if not any(v == u for u in a):
return False
return True
def match(a, b):
return contains(a, b) and contains(b, a)
target = [1,2,3,4,5]
data = ([3,5,1,2,4], [1,2,3,4,5,6], [1,2,3,4,6], [3,1,2,1,4])
print(target)
for seq in data:
print(seq, contains(target, seq), contains(seq, target), match(target, seq))
output
[1, 2, 3, 4, 5]
[3, 5, 1, 2, 4] True True True
[1, 2, 3, 4, 5, 6] False True False
[1, 2, 3, 4, 6] False False False
[3, 1, 2, 1, 4] True False False