Check list overlap with list comprehensions

Viewed 243

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!

3 Answers

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.

Use sets, not list comprehensions:

c = list(set(a) & set(b))
print(c)
# [2, 3, 6, 7, 8, 9]

From the docs:

A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

    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]
    c=[]
    for i in max(a,b):
        if i in min(a, b) and i not in c:
            c.append(i) 
    print(c)
Related