Explore Courses Blog Tutorials Interview Questions
+1 vote
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]


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

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jan 18, 2020 in Python by Rajesh Malhotra (19.9k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.5k answers


108k users

Browse Categories