backtrack
backtrack

Reputation: 8144

Set operation in python

I have a two list of objects say example

L1 = [2,3,4]
L2 = [1,2]

i want to have two different list.

1) matching items 2) not matching items

I am able to get the matching element #1 like below

match = [x for x in L1 if x in L2]

but how can i get the not matching elements in a efficient way.

I can use not in but is there any other way of doing this.

Thanks ,

Upvotes: 3

Views: 332

Answers (5)

lmiguelvargasf
lmiguelvargasf

Reputation: 69755

I think you can take advantage of the built-in type set which basically has unordered distinct elements. I also encourage you to try the shorthand notation to perform the operations union, intersection, and difference.

>>> s1 = set(L1)
>>> s2 = set(L2)
>>> s1 | s2 # union
{1, 2, 3, 4}
>>> s1 & s2 # intersection
{2}
>>> s1 - s2 # difference
{3, 4}
>>> s1 ^ s2 # symmetric difference
{1, 3, 4}

A refresher of set operations from a math perspective

Suppose A and B are sets.

  • The union of A and B is the set A∪B = {x: x ∈ A or x ∈ B}
  • The intersection of A and B is the set A∩B = {x: x ∈ A and x ∈ B}
  • The difference of A and B is the set A-B = {x: x ∈ A and x ∉ B}
  • The symmetric difference of A and B is the set A∆B = A∪B - A∩B

Upvotes: 0

Vivek Sable
Vivek Sable

Reputation: 10223

  1. set is best way to get matching and non matching items.

By List compression:

>>> L1 = [2,3,4]
>>> L2 = [1,2]
>>> [i for i in L1 if i not in  L2]
[3, 4]
>>> [i for i in L1 if i in L2]
[2]
>>> [i for x in L2 if i not in L1]
[1]
>>> [i for i in L1 if i not in  L2] +  [i for i in L2 if i not in L1]
[3, 4, 1]

Upvotes: 1

Siddhartha
Siddhartha

Reputation: 113

Here's a possibility:

not_match=[x for x in L1 if x not in L2] + [x for x in L2 if x not in L1]

Upvotes: 1

Christian Tapia
Christian Tapia

Reputation: 34146

You can get it by using match:

no_match = [x for x in L1 + L2 if x not in match]

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117876

You can use the various set methods such as intersection, difference, symmetric_difference, and union

>>> L1 = [2,3,4]
>>> L2 = [1,2]
>>> set(L1).intersection(L2)
{2}
>>> set(L1).difference(L2)
{3, 4}
>>> set(L1).symmetric_difference(L2)
{1, 3, 4}
>>> set(L1).union(L2)
{1, 2, 3, 4}

Upvotes: 3

Related Questions