-1

I am trying to write a function that will get 2 lists, find the intersection points between them, and return a new list with these intersection points, and the new list won't contain the same element more than once.
For example:

intersection([1,2,3,4], [8,3,9])
[3]

I've tried the following:

print(list(filter(lambda x: x in list2, list1)))

The thing is, if do, for example:

intersection([1,2,3,3,4], [8,3,9])

The result would be [3,3].

How do I make it so there will o only be one 3, in the same line of code?

Thanks!

natitati
  • 35
  • 4

5 Answers5

0

Try: list(set(intersection([1,2,3,3,4], [8,3,9])))

FreeMarket
  • 11
  • 1
  • 1
0

The easy way is to pass by sets :

L = [1,2,3]
M = [4,2,2,3,3]

inter = list( set(L).intersection(M) )
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
0

Why not use set and convert the result back to list as follow:

l = [1, 2, 3, 3, 4]
l2 = [8, 3, 9]
list(set(l).intersection(set(l2)))

outpu:

[3]
pyzer
  • 122
  • 7
  • This works, but `set.intersection(set(l), set(l2))` is a bit of a misuse; it's a method of `set`s, and is usually called *on* a set. This only works because you explicitly `set`ify the first argument (the `self` it would get if you called it on an actual `set`). The idiomatic approaches would be `set(l).intersection(l2)` (no need to `set`-ify arguments to method) or `set(l) & set(l2)` (operators require both sides to be `set`s). – ShadowRanger Oct 16 '21 at 20:25
  • You are absolutely right! I've updated my code to show exactly that. thanks! – pyzer Oct 16 '21 at 20:28
  • hey, this worked. However, another problem that I seem to face is that the set comes out sorted, if I understand right. for example, I pass: list1 = [5, 3] list2 = [5, 4, 3] This returns: [3. 5] But I want it to return: [5, 3], like in the order the elements are in the list. Is there any way to do it? Thanks! – natitati Oct 16 '21 at 20:38
  • You can try installing OrderSet library from order_set package and it can do exactly what you are looking to achieve. ```from ordered_set import OrderedSet list(OrderedSet(list1).intersection(list2))``` would produce ```[5, 3] ``` [ordered-set](https://pypi.org/project/ordered-set/) – pyzer Oct 16 '21 at 20:51
  • This worked perfectly. Much appreciated! – natitati Oct 16 '21 at 21:03
0

Use set.intesection:

def intersection(l1, l2):
    return list(set(l1).intersection(l2))

intersection([1,2,3,4], [8,3,9])
# [3]
mozway
  • 194,879
  • 13
  • 39
  • 75
0

How to get just a [3]

x = list(set(filter(lambda x: x in [1,2,3,3,4], [8,3,3,9])))
print(x)

output:

[3]

PythonProgrammi
  • 22,305
  • 3
  • 41
  • 34