monish kumar k
monish kumar k

Reputation: 29

Getting unique values in python using List Comprehension technique

I want to get the values that appear in one of the lists but not in the others. I even tried using '<>', it says invalid syntax. I am trying using list comprehensions.

com_list = []
a1 = [1,2,3,4,5]
b1 = [6,4,2,1]
come_list = [a for a in a1 for b in b1 if a != b ]

Output: [1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5]

My expected output would be `[3, 5, 6]

Upvotes: 0

Views: 554

Answers (2)

Leo Arad
Leo Arad

Reputation: 4472

You can do

come_list =[i for i in list((set(a1) - set(b1))) + list((set(b1) - set(a1)))]
print(come_list)

Output

[3, 5, 6]

This new list contains all unique numbers for both of the lists together.
the problem with this line come_list = [a for a in a1 for b in b1 if a != b ] is that the items iterating over each item in the first list over all the items in the second list to check if it's inited but it's not giving unique numbers between both.

Upvotes: 0

Thierry Lathuille
Thierry Lathuille

Reputation: 24280

What you want is called symmetric difference, you can do:

a1 = [1,2,3,4,5]
b1 = [6,4,2,1]

set(a1).symmetric_difference(b1)
# {3, 5, 6}

which you can also write as:

set(a1) ^ set(b1)

If you really want a list in the end, just convert it:

list(set(a1) ^ set(b1))
# [3, 5, 6]

a1 = [1,2,3,4,5] b1 = [6,4,2,1]


If you really want to do that using list comprehensions, well, here it is, but it's really not the right thing to do here.

A totally inefficient version:

# Don't do that !

sym_diff = [x for x in a1+b1 if x in a1 and x not in b1 or x in b1 and x not in a1]
print(sym_diff)

# [3, 5, 6]

It would be a bit better using sets to test membership efficiently:

# Don't do that either

a1 = set([1,2,3,4,5])
b1 = set([6,4,2,1])

sym_diff = [x for x in a1|b1 if x in a1 and x not in b1 or x in b1 and x not in a1]
print(sym_diff)

# [3, 5, 6]

But if you start using sets, which is the right thing to do here, use them all the way properly and use symmetric_difference.

Upvotes: 1

Related Questions