Search code examples
pythonlistuniqueelement

How to get values unique to each list for three lists?


I have three lists, and I am looking to get a list of values that are unique in each respective lists.

For example, if i have three lists:

a = [1, 2, 3]
b = [2, 4, 5]
c = [3, 2, 6]

The expected output would keep elements in the list that are not in the other two lists:

only_in_a = [1]
only_in_b = [4,5]
only_in_c = [6]

I've been running a simple for loop to loop through the array:

for i in a:
    if i not in b:
        if i not in c:
           print (i)

And I pipe the output into their own text files. However, my input lists goes up to tens of millions, and this process is slow. Does anyone have suggestions on a faster, more efficient method?

Thanks.


Solution

  • This looks like a job for Python sets.

    set_a = set(a)
    set_b = set(b)
    set_c = set(c)
    
    only_in_a = set_a - set_b - set_c
    only_in_b = set_b - set_a - set_c
    only_in_c = set_c - set_a - set_b