-2

I have two lists that I want to remove the same words from the lists. I use this code but it doesn't work:

a = ['go ing', 'watch TV', 'ice cream', 'sit ting', 'note book']
b = ['go ing', 'watching TV', 'ice cream', 'sit ing', 'notebook']

if a[i] == b[i]:
    try:
        a.remove(i)
        b.remove(i)
    except:
        pass

My desired output is a = ['watch TV', 'sit ting', 'note book']. Could anyone help me?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Soheila
  • 45
  • 5
  • `[i for i in a if i not in b]` if order matters else `set(a).difference(b)` – Epsi95 Feb 25 '21 at 14:26
  • But from your question it seems like you want a list where all the elements will be present for which it will not be present in both the list. In that case you can use `(set(a).union(b)).difference(set(a).intersection(b))` – Epsi95 Feb 25 '21 at 14:29
  • Does this answer your question? [Python, compute list difference](https://stackoverflow.com/questions/6486450/python-compute-list-difference) – Tomerikoo Apr 23 '21 at 10:16

1 Answers1

0

First of all your answer seems unclear to me, but I guess you want to do this

a = ['go ing','watch TV', 'ice cream','sit ting','note book']
b = ['go ing','watching TV','ice cream','sit ing','notebook']

set(a).intersection(set(b))
>>> {'go ing', 'ice cream'}

set(a).difference(set(b))
>>> {'sit ting', 'watch TV', 'note book'}

You can use Set to perform operations like Difference, Intersection, Union, Symmetric Difference, etc.

rish_hyun
  • 451
  • 1
  • 7
  • 13