Search code examples
pythonlist-comprehensionoverlap

Check list overlap with list comprehensions


I have a script in python that generate 2 random lists with different sizes and return a third list that contains only the elements that are common between the 2 lists (without duplicates) using list comprehensions

Example:

a = [3, 8, 9, 6, 5, 3, 7, 8, 2, 10]
b = [7, 13, 20, 12, 12, 2, 6, 1, 2, 8, 19, 3, 15, 16, 14, 22, 22, 4, 9, 15, 8, 13]

My result list is

c = [7, 2, 6, 2, 8, 3, 9, 8]

But it should be

c = [7, 6, 2, 8, 3, 9]

Here is what I've done:

c = [i for i in max(a, b) if i in min(a, b) and i not in c]

Thanks in advance!


Solution

  • You could use sets in the following way:

    c = list(set(a).intersection(set(b)))
    

    This will give you:

    [2, 3, 6, 7, 8, 9]
    

    This works because set items are unordered, unchangeable, and do not allow duplicate values. Combine that with the intersection method you will get the result.