3
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']
Tobbe
  • 1,825
  • 3
  • 21
  • 37
Thomas N T
  • 459
  • 1
  • 3
  • 14

4 Answers4

4

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']
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
1

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**']
Ashwani Agarwal
  • 1,279
  • 9
  • 30
1

If you want to

  1. remove * from List2 items
  2. elements not in list1

Try:

>>> list = [x.replace('*', '') for x in list2 if x not in list1]
>>> list
['water resistant', 'red strap', 'digital and analog', 'stainless steel']
>>> 
Praveen
  • 8,945
  • 4
  • 31
  • 49
0

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']
kilojoules
  • 9,768
  • 18
  • 77
  • 149
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Peter Brittain Sep 01 '15 at 07:51
  • What could make those 2 lines of code any clearer? Maybe say that it's a "list comprehension" so that someone who does not recognise the syntax can look it up? But the first time I saw one my thoughts were "awesome" and after playing with it a bit, "does what it says on the tin". – nigel222 Sep 01 '15 at 11:05