Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
3 views
in Python by (210 points)

I am having two lists

list1 = ['Apple', 'Orange', 'Grapes', 'Banana']
list2 = ['Apple', 'Orange']

I want to generate the list3 of those items which are not present in the list2 from list1. For an ex I have to get:

list3 = ['Grapes', 'Banana']

1 Answer

0 votes
by (10.9k points)

There are various ways of doing this some are as follows:

1. In [5]: list(set(list1) - set(list2))

    Out[5]: ['Apple', 'Orange']

 2. def diff(list1,list2):

    x = set(list1).union(set(list2))

y = set(list1).intersection(set(list2))

return list(x - y)

 3. list3 = [item for item in list1 if item not in list2]

Note:

If you want to get difference between two lists containing numbers then:

In [5]: set([1, 3]) - set([4, 3])

Out[5]: set([1])

But it is expected to print set([1,4]) ,so for that you will have to use :

def diff(list1, list2):

return list(set(list1).symmetric_difference(set(list2)))

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...