3

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 ,

backtrack
  • 7,996
  • 5
  • 52
  • 99

5 Answers5

3

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}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

You can get it by using match:

no_match = [x for x in L1 + L2 if x not in match]
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
  • Is there a way to get both match and not match in a single iteration meaning without using two loops like, match , not_match = [something] – backtrack Feb 26 '15 at 15:06
  • 1
    @Backtrack See [here](https://stackoverflow.com/questions/949098/python-split-a-list-based-on-a-condition) – Cory Kramer Feb 26 '15 at 15:08
1

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]
Siddhartha
  • 113
  • 1
  • 5
1
  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]
Vivek Sable
  • 9,938
  • 3
  • 40
  • 56
0

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
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228