user13110485
user13110485

Reputation:

Compare each element in a list with every element in another list

I have two lists, words = ["hello", "how", "hello", "are", "you"] and match = ["hello, "sonic"]. How do I compare in such a way that if the first element in match is the same as the first element in words and (same for second, third etc), then append 'true' to another list?

So for the above lists, I would want results = ["true", "false", true", "false", "false"]. I currently have the following but this only appends true and never false. I know that it is because the else statement never executes as 'hello' is always in words[]. I know I am quite far off the mark here.

for i in match:
    if i in words:
        results.append('true')
    else:
        results.append('false')

I hope I explained it well.

Upvotes: 0

Views: 120

Answers (1)

AbbeGijly
AbbeGijly

Reputation: 1211

Try using the python "in" syntax:

match = ["hello", "sonic"]
words = ["hello", "how", "hello", "are", "you"]
results = [w in match for w in words]

or if you want the strings "true" or "false"

results = [str(w in match).lower() for w in words]

Upvotes: 3

Related Questions