Reputation: 37
I am a beginner in python and I am trying to write a function that takes in two lists, and for each item in the first list, looks into the second list, and compares each item in the first list with each item in the second list. It needs to return a new list containing the all items that do not appear in first list.
So for instance, given a list:
list1 = ['yellow', 'blue', 'green']
and the second list:
list2 = ['orange', 'green', 'blue', 'pink', 'yellow']
it should return a list of only the items in list2 that are not in list1, like this:
['orange', 'pink']
I have written many functions but they keep returning duplicates, I really appreciate any help on this!
def different_colors(list1, list2):
newlist = []
for color in list1:
newlist = []
for color2 in list2:
if color1 != color2:
newlist.append(color2)
return newlist
Upvotes: 0
Views: 157
Reputation: 45
You can use python sets (http://docs.python.org/2/library/stdtypes.html#set):
s1 = set(list1)
s2 = set(list2)
list(s2.difference(s1))
Upvotes: 1
Reputation: 304175
It's a little simpler than you think
newlist = []
for color in list2:
if color not in list1:
newlist.append(color2)
return newlist
converting list1
to a set would make this more efficient
Upvotes: 0
Reputation: 76955
Try using sets:
>>> list(set(list2) - set(list1))
['orange', 'pink']
Upvotes: 2