Stijnemans
Stijnemans

Reputation: 21

Python compare 2 lists with duplicates

I want to compare 2 lists and return the matches in a list. But when I do this I don't get the matches that are identical.

    matches = []
    l1 = [2, 3, 4, 5, 6]
    l2 = [2, 4, 4]
    for n in l2:
        if n in l1:
        matches.append(n)
        print(matches)

this returns:

   [2, 4]  

and what I would like it to return is:

   [2, 4, 4]

Upvotes: 2

Views: 131

Answers (3)

Andrew V.D
Andrew V.D

Reputation: 1

Python mainly depends on the indentation and hence it becomes very important to indent a code to get the required output

The correct code is :

matches = []
l1 = [2, 3, 4, 5, 6]
l2 = [2, 4, 4]
for n in l2:
    if n in l1:
        matches.append(n)
print(matches)

We get : [2,4,4]

Upvotes: 0

Sash Sinha
Sash Sinha

Reputation: 22275

Consider using a list-comprehension:

>>> l1 = [2, 3, 4, 5, 6]
>>> l2 = [2, 4, 4]
>>> l1_set = set(l1)  # Convert to set for O(1) lookup time.
>>> matches = [n for n in l2 if n in l1_set]
>>> matches
[2, 4, 4]

Upvotes: 1

Paolo Tormon
Paolo Tormon

Reputation: 341

This actually works, you just missed the indent.

matches = []
l1 = [2, 3, 4, 5, 6]
l2 = [2, 4, 4]
for n in l2:
    if n in l1:
        matches.append(n)
print(matches)

Output: [2, 4, 4]

Upvotes: 2

Related Questions