I am beginner in learning Python and I have two lists
list1 = [\'product\',\'document\',\'light\',\'time\',\'run\']
list2 = [\'survival\',\'shop\',\'document\',\
The answered solution works perfectly well, but I would like to propose another one using the set
data structure since this is the most adapted one for this kind of problem:
list1 = ['product','document','light','time','run']
list2 = ['survival','shop','document','run']
set1 = set(list1)
set2 = set(list2)
matching_words = set1.intersection(set2)
# {'document', 'run'}
nonmatching_words = set1.symmetric_difference(set2)
# {'time', 'light', 'shop', 'survival', 'product'}
Please note that the order of the elements are random.
However, if the order is not important, you might even want to work with sets from end to end:
# DECLARING A SET
set1 = {'product','document','light','time','run'}
set2 = {'survival','shop','document','run'}
# Notice the use of {} instead of []
# FOR LOOP
for word in matching_words:
print(word)
# document
# run
If you absolutely need to have a list, you can transform back the results (order still unpredictable):
matching_words = list(matching_words)
nonmatching_words = list(nonmatching_words)