Jared
Jared

Reputation: 95

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.

Upvotes: 1

Views: 520

Answers (2)

Julien
Julien

Reputation: 15071

Use sets?

a = {1, 2, 3}
b = {2, 4, 5}
c = {3, 2, 6}

only_in_a = a-b-c
only_in_b = b-a-c
only_in_c = c-a-b

Upvotes: 3

Attila Viniczai
Attila Viniczai

Reputation: 693

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

Upvotes: 5

Related Questions