11

I have tried for a while but can't find a simple way to join 2 lists or arrays based only on common values. Similar to an SQL inner join but with arrays/lists and not dict, or some other data type. eg.

a = [1, 2, 3]
b = [2, 3, 4]
join(a, b)

prints

[2, 3]

seems so simple but lacking from python or numpy.

Jacques MALAPRADE
  • 963
  • 4
  • 13
  • 28

2 Answers2

32

Probably a duplicate, but in case it is not:

>>> a = [1,2,3]
>>> b = [2,3,4]
>>> list(set(a) & set(b))
[2, 3]

For large lists (external data), see this S.O. answer.

Community
  • 1
  • 1
Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • I am not familiar with the Binary AND Operator being used with set()s. In this scenario, is the & Operator operating on the bits of each of the element within the two sets, or is it operating on the element (as a whole) of the two sets? – Yi Zong Kuang Dec 16 '21 at 16:49
  • 1
    For sets, `&` performs set intersection, returning a new set containing all the elements that are in both `a` and `b`. It has nothing to do with bits. If the `&` operator is used between two `int` operands then it will perform a bitwise AND. In Python you can create your own classes and make the operators do pretty much anything you want. This is generally considered a good thing when used properly. By the way, the Python `set` class makes the `|` do union, and the `^` do disjoint union, and `-` do set subtraction. – Ray Toal Dec 16 '21 at 23:58
  • Thank you for the responding! – Yi Zong Kuang Dec 17 '21 at 17:37
11

If you need to keep the list in the same order as in a:

a = [1, 2, 3]
b = [2, 3, 4]
c = [x for x in a if x in b]

if the order is not important, use Ray answers, that should be faster, but not guaranteed to keep the list order the same as the order of the elements in a.

John83
  • 143
  • 5