Reputation: 31
If you have two lists that share a number of elements, how do you find the matches, and create a new list of these elements?
Ex.)
first = ['cat','dog','parrot','fish']
second = ['fish', 'hamster', 'mouse', 'dog']
how would make a function/for-loop that searches for the matches and puts them into a list?
matches = ['dog', 'fish']
Upvotes: 0
Views: 28
Reputation: 51
Try this:
match = []
for i in first:
for j in second:
if i == j:
match.append(i)
print('Match: {}'.format(match))
Upvotes: 0
Reputation: 26039
You can do set.intersection
if order does not matter:
list(set(first).intersection(second))
Or if order matters, you can do a list comprehension:
[x for x in first if x in second]
Upvotes: 1