Home > other >  Python compare 2 lists with duplicates
Python compare 2 lists with duplicates

Time:04-17

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]

CodePudding user response:

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]

CodePudding user response:

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]

CodePudding user response:

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]

  • Related