Search code examples
pythonlistlist-comprehension

How do I minimize a list so there will only be only one of each element in python - in one line?


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!


Solution

  • 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]