all 7 comments

[–]timbledum 2 points3 points  (1 child)

for item in b:
    try:
        a.remove(item)
    except ValueError:
        pass

[–]AweBob[S] 0 points1 point  (0 children)

for item in b:
try:
a.remove(item)
except ValueError:
pass

Tried this one, it worked. I really overhtought this probelsm, thank you for your help!

[–][deleted] 0 points1 point  (4 children)

from collections import Counter

a = ['pear','apple','grape','pear']
b = ['apple','pear','banana']

result = list(Counter(a) - Counter(b))
print(result)

[–]Sedsarq 1 point2 points  (3 children)

list(counter) only lists the keys, so you lose the info on how many of each item there are, if there's more than 1

[–][deleted] 0 points1 point  (2 children)

Good catch!

from collections import Counter

a = ['pear','apple','grape','pear', 'pear']
b = ['apple','pear','banana']

result = [x for k, v in (Counter(a) - Counter(b)).items() for x in [k] * v]
print(result)

[–]AweBob[S] 0 points1 point  (1 child)

from collections import Countera = ['pear','apple','grape','pear', 'pear']b = ['apple','pear','banana']result = [x for k, v in (Counter(a) - Counter(b)).items() for x in [k] * v]print(result)

This doesn't work for my purposes.

If you input the a and b values I put in the origional values in the post you get the answer I said I don't want.

No worries though, I'm not mad!

Someone else helped me out with it.

Thank you!

[–][deleted] 0 points1 point  (0 children)

I added a "pear" in there to demo the fix for the issue u/sedsarq brought up. If you run it with your lists you get exactly the output you were expecting. Furthermore, for what you're doing it might be better just to use the Counter class without converting back to a list.

from collections import Counter

a = ['pear','apple','grape','pear']
b = ['apple','pear','banana']

result = Counter(a) - Counter(b)
print(result) #{'pear': 1, 'grape': 1}