0

From two lists, return a list that contains only the elements that are common between the 2 imput lists. Without duplicates.

Imput:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

My solution:

common_list = [i for i in a if i in b]

My output:

[1, 1, 2, 3, 5, 8, 13]

Output i need:

[1, 2, 3, 5, 8, 13]
  • Thank you for your answers, you are right but I want to do this via list-comprehension. I just don't understand them well and trying to figure out how to correct what I wrote. – Bartek Węgrzyn Aug 13 '20 at 19:24
  • 1
    if you don't use sets you'll have O(n*2) complexity. And you can't do that with list comprehension because you need to keep track of the already existing elements. – Jean-François Fabre Aug 13 '20 at 19:26
  • you can use your solution, then filter out the elements whose count is not 1 using another list comprehension. Or chain 2 list comprehensions. But it's inefficient. – Jean-François Fabre Aug 13 '20 at 19:30
  • 1
    If you really want to use only lists, you can do this: `common_list = []; common_list.extend(i for i in a if i in b and i not in common_list)` – GZ0 Aug 13 '20 at 19:32
  • It was exactly what I needed! I did the same but with out: common_list = []; at the beginning and I did no have idea why it doesn't work. I'm just learning to program and I don't understand much yet. Thank you very much @GZ0 – Bartek Węgrzyn Aug 13 '20 at 19:43
  • I understand using set() is better, but it's just for learning purpose – Bartek Węgrzyn Aug 13 '20 at 19:46
  • @BartekWęgrzyn `common_list` needs to be initialized before being used and updated during its extension. – GZ0 Aug 13 '20 at 19:57

3 Answers3

3

You can use the set operation

In [13]: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    ...: b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

In [14]: list(set(a) & set(b))
Out[14]: [1, 2, 3, 5, 8, 13]

The problem with your code is the duplicate elements in the output.. You can avoid that by applying set operator on the output

common_list = list(set(i for i in a if i in b))
Jab
  • 26,853
  • 21
  • 75
  • 114
2

You can use set intersection:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

out = list(set(a).intersection(set(b)))
print(out)

Output:

[1, 2, 3, 5, 8, 13]
Vicrobot
  • 3,795
  • 1
  • 17
  • 31
2

As an alternative to Arun's answer, you can also do this:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
set(a).intersection(b)

Which I find more readable than set(a) & set(b) because that feels a little too "magical" to me.

Julia
  • 1,950
  • 1
  • 9
  • 22