Python Forum

Full Version: Output difference from 2 lists of different sizes with words
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone.

Let say I have the following 2 lists with words of different sizes for example,
list0=['guava','apple','banana','strawberry','orange']
list1=['orange','pineapple','apple']
difference=list(set(list0).symmetric_difference(list1))
print(difference)
Output:
['banana', 'guava', 'strawberry', 'pineapple']
Output above is the mix of words that are not present in both sets that I am only able to do at this stage.

However, I'd like to seek your help on how can I achieve the the following desired output please? Huh
Output:
Words appear in first list and not second list = guava, banana, strawberry Words appear in second list and not first list = pineapple
Thanks a lot and have a great weekend
you should use builtin set types, see: https://docs.python.org/3/library/stdtyp...0types#set
You can use set operation to achieve desired result:

>>> list0=['guava','apple','banana','strawberry','orange']
>>> list1=['orange','pineapple','apple']
>>> set(list0) - set(list1)
{'strawberry', 'guava', 'banana'}
>>> set(list1) - set(list0)
{'pineapple'}
However, sets are unordered. If order is important then list comprehension could be used:

>>> [item for item in list0 if item not in list1]
['guava', 'banana', 'strawberry']
>>> [item for item in list1 if item not in list0]
['pineapple']
(Sep-02-2022, 02:55 PM)Larz60+ Wrote: [ -> ]you should use builtin set types, see: https://docs.python.org/3/library/stdtyp...0types#set

Thanks for the info Smile
(Sep-02-2022, 03:48 PM)perfringo Wrote: [ -> ]You can use set operation to achieve desired result:

>>> list0=['guava','apple','banana','strawberry','orange']
>>> list1=['orange','pineapple','apple']
>>> set(list0) - set(list1)
{'strawberry', 'guava', 'banana'}
>>> set(list1) - set(list0)
{'pineapple'}
However, sets are unordered. If order is important then list comprehension could be used:

>>> [item for item in list0 if item not in list1]
['guava', 'banana', 'strawberry']
>>> [item for item in list1 if item not in list0]
['pineapple']

Thanks for the solutions Smile
I'd do it this way:
>>> set1 = set(['guava','apple','banana','strawberry','orange'])
>>> set2 = set(['orange','pineapple','apple'])
>>> set3 = set(['banana', 'guava', 'strawberry', 'pineapple'])
>>> set1.difference(set2)
{'strawberry', 'banana', 'guava'}
>>> set3.difference(set1)
{'pineapple'}