user3447849
user3447849

Reputation: 37

python creating a list from two other lists

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

Answers (4)

Stein Roald
Stein Roald

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

John La Rooy
John La Rooy

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

Rafe Kettler
Rafe Kettler

Reputation: 76955

Try using sets:

>>> list(set(list2) - set(list1))
['orange', 'pink']

Upvotes: 2

Eric
Eric

Reputation: 97591

Use sets:

>>> set(list2) - set(list1)
{'orange', 'pink'}

Upvotes: 3

Related Questions