Lzhelis
Lzhelis

Reputation: 41

Python: How to generate list with items repeating in two lists

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?

Upvotes: 2

Views: 1196

Answers (4)

Idrisi_Kasim
Idrisi_Kasim

Reputation: 91

Try this:

[common for common in list_1 if common in list_2]

Happy learning...:)

Upvotes: 0

nonamer92
nonamer92

Reputation: 1917

read about collections.Counter

from collections import Counter

list_3 = list((Counter(list_1) & Counter(list_2)).elements())

Upvotes: 2

chepner
chepner

Reputation: 531075

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`.

Upvotes: 3

kjmerf
kjmerf

Reputation: 4345

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

Upvotes: 2

Related Questions