2

I have two lists of items:

list_1 = ['A', 'B', 'C', 'C', 'D']
list_2 = ['C', 'C', 'F', 'A', 'G', 'D', 'C']

I want to create a new list with the elements that are in the two lists. Like this:

['A', 'C', 'C', 'D']

Notice that it should take in mind that any item can repeat in list several times and should be in the new list as many times as it is repeated in both lists. For instance, 'C' is repeated 2 times in list_1 and 3 times in list_2 so it appears 2 times in the result.

The classic method to do it will be:

import copy
result = []
list_2 = fruit_list_2.copy()
for fruit in fruit_list_1:
  if fruit in list_2:
    result.append(fruit)
    list_2.remove(fruit)

but I am interested to do it by generation lists: [number for number in numbers if number > 0]. Is it possible?

Cristian Ramon-Cortes
  • 1,838
  • 1
  • 19
  • 32
Lzhelis
  • 41
  • 1
  • 6

4 Answers4

3

If you aren't terribly concerned about the ordering of the new list, you can use collections.Counter.

>>> list((Counter(list_1) & Counter(list_2)).elements())
['A', 'C', 'C', 'D']

& takes the intersection of the two as multi-sets, with the minimum count used for common elements. The elements method returns the items in the result as an iterator, hence the list wrapper`.

chepner
  • 497,756
  • 71
  • 530
  • 681
2

I think it's as simple as:

list_1 = ['A', 'B', 'C', 'C', 'D']
list_2 = ['C', 'C', 'F', 'A', 'G', 'D', 'C']

list_3 = [x for x in list_1 if x in list_2]

print(list_3)

# returns ['A', 'C', 'C', 'D']
kjmerf
  • 4,275
  • 3
  • 21
  • 29
2

read about collections.Counter

from collections import Counter

list_3 = list((Counter(list_1) & Counter(list_2)).elements())
nonamer92
  • 1,887
  • 1
  • 13
  • 24
0

Try this:

[common for common in list_1 if common in list_2]

Happy learning...:)

Idrisi_Kasim
  • 81
  • 1
  • 2
  • 1
    no.. it is easy but you have bug in case: list_1 = ['A', 'B', 'C', 'C', 'C', 'L', 'C'] list_2 = ['C', 'C', 'F', 'A', 'N', 'L', 'C'] new_list will be: ['A', 'C', 'C', 'C', 'L', 'C'] - here 4C but need 3C – Lzhelis Nov 08 '19 at 21:55