Reputation: 459
list1=['water', 'analog', 'resistance', 'color', 'strap','men', 'stainless', 'timepiece','brown','fast']
list2=['water resistant','water','red strap','digital and analog','analog', 'men', 'stainless steel']
So that output will be
list=['water resistant','red strap','digital and analog','stainless steel']
Upvotes: 3
Views: 135
Reputation: 10083
You could do it this way. Iterate through a list of list1 words which are in list2, then use the iterator to remove words. This does not work for repeated words.
>>> for s in [a for a in list1[:] if a in list2[:]]:
... list2.remove(s)
...
>>> list2
['water resistant', 'red strap', 'digital and analog', 'stainless steel']
Upvotes: 0
Reputation: 9345
If you want to
*
from List2
itemslist1
Try:
>>> list = [x.replace('*', '') for x in list2 if x not in list1]
>>> list
['water resistant', 'red strap', 'digital and analog', 'stainless steel']
>>>
Upvotes: 1
Reputation: 1319
You can use set
for this. Also with set
you won't have any item duplicated.
Here is output from Python Shell
>>> set1 = set(list1)
>>> set2 = set(list2)
>>> set1
set(['brown', 'timepiece', 'color', 'stainless', 'men', 'resistance', 'fast', 'strap', 'water', 'analog'])
>>> set1-set2
set(['brown', 'timepiece', 'color', 'stainless', 'resistance', 'fast', 'strap'])
>>> set2-set1
set(['red strap', '**water resistant**', '**stainless steel**', '**digital and analog**'])
>>> for each in (set2-set1):
print each
red strap
**water resistant**
**stainless steel**
**digital and analog**
>>> list3 = list(set2-set1)
>>> list3
['red strap', '**water resistant**', '**stainless steel**', '**digital and analog**']
Upvotes: 1
Reputation: 20015
You could use set operations:
list(set(list2) - set(list1))
Possible result:
['red strap', 'digital and analog', 'stainless steel', 'water resistant']
If you want to preserve the order you could do the following:
s = set(list1)
[x for x in list2 if x not in s]
Result:
['water resistant', 'red strap', 'digital and analog', 'stainless steel']
Upvotes: 4