I'm pretty new to Python and am getting a little confused as to what you can and can't do with lists. I have two lists that I want to compare and return matching and nonmatching elements in a binary format. List1
is of constant length, while the length of List2
differs (but is always shorter than List1
).
For example:
List1 = ['dog', 'cat', 'pig', 'donkey']
List2 = ['dog', 'cat', 'donkey']
Output wanted:
List3 = [1, 1, 0, 1]
The code I have so far is:
def match_nonmatch(List1, List2):
List3 = []
for i in range(len(List1)):
for j in range(len(List2)):
if List1[i] == List2[j]:
List3.append(1)
else:
List3.append(0)
return List3
I am able to return the matches when I compare the lists, but when I include the else statement shown above to return the nonmatches I end up with a list that is way longer than it should be. For instance, when I use a list comparing 60 items, I get a list that contains 3600 items rather than 60.
I'd appreciate it if someone could explain to me the problem with my code as it currently stands and suggest how I could modify the code so it does what I want.