0

Lists being compared

list1 = ['Q, 'U', 'Z', 'Z']

List2 = ['Q, 'U', 'I', 'Z']

My query

common = []
for letter in list1: # QUZZ
    if letter in list2: # QUIZ --- this is the problematic condition (it is add 2 ZZ's instead of 1)
        common.append(letter)
print(common)

Expected Output

Common = ['Q, 'U', 'Z']

Actual Output

Common = ['Q, 'U', 'Z', 'Z']

To add, the query should also work for the reverse condition. I have tried using sets, but that doesn't work for the second condition

list1 = ['Z','Z','Z','Z','E','E']
list2= ['Z', 'Z', 'Z']


print(list(set([x for x in list1 if x in list2])))

Expected Output: ''' ['Z','Z','Z']

'''

Actual Output:

['Z']
JRose
  • 1,382
  • 2
  • 5
  • 18
gaurav8936
  • 43
  • 7
  • 1
    Use `set` to remove the duplicates - `list(set([x for x in list1 if x in List2]))` – It_is_Chris Oct 03 '22 at 20:47
  • 2
    @It_is_Chris Or just `set(list1).intersection(list2)` – DeepSpace Oct 03 '22 at 20:53
  • You could also use a counter for this if you want to preserve matching duplicates: `list((Counter(word1) & Counter(word2)).elements())` – flakes Oct 03 '22 at 21:00
  • @flakes thank you. I think the Counter solution will work -- giving it a shot. Was hoping there was an alternate to using collections – gaurav8936 Oct 03 '22 at 21:13
  • @ZibaJoon I wouldn't worry about using collections. That module is built into the core libraries (no pip required). – flakes Oct 04 '22 at 15:48

2 Answers2

1

If you use a set you can use the & operator, which for sets does an intersection. This will eliminate duplicates and find common elements.

Edit: For your problem you will actually need a multiset. I recommend using the multiset package which you can install with pip install multiset or pip3 install multiset if you're using python3.

from multiset import Multiset

list1 = ['Z','Z','Z','Z','E','E']

list2= ['Z', 'Z', 'Z']

print(Multiset(list1) & Multiset(list2)) # Output: {'Z', 'Z', 'Z'}
JRose
  • 1,382
  • 2
  • 5
  • 18
1

As @It_is_Chris said in the comment you can use sets to remove duplicates. Sets also have a method to find common items:

list1 = ['Q, 'U', 'Z', 'Z']
list2 = ['Q, 'U', 'I', 'Z']
common = set(list1).intersection(set(list2))

The output is now a set, but can be converted to a list if needed.

Carlos Melus
  • 1,472
  • 2
  • 7
  • 12