N K Han
N K Han

Reputation: 31

In Python, if you have two lists that share a number of elements, how do you create a new list with the matches?

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

Answers (2)

Sahil Chawla
Sahil Chawla

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

Austin
Austin

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

Related Questions