Remove list from list in Python

PythonListPython 2.7

Python Problem Overview


> Possible Duplicate:
> Get difference from two lists in Python

What is a simplified way of doing this? I have been trying on my own, and I can't figure it out. list a and list b, the new list should have items that are only in list a. So:

a = apple, carrot, lemon
b = pineapple, apple, tomato
new_list = carrot, lemon

I tried writing code, but every time it always returns the whole list a to me.

Python Solutions


Solution 1 - Python

You can write this using a list comprehension which tells us quite literally which elements need to end up in new_list:

a = ['apple', 'carrot', 'lemon']
b = ['pineapple', 'apple', 'tomato']

# This gives us: new_list = ['carrot' , 'lemon']
new_list = [fruit for fruit in a if fruit not in b]

Or, using a for loop:

new_list = []
for fruit in a:
    if fruit not in b:
        new_list.append(fruit)

As you can see these approaches are quite similar which is why Python also has list comprehensions to easily construct lists.

Solution 2 - Python

You can use a set:

# Assume a, b are Python lists

# Create sets of a,b
setA = set(a)
setB = set(b)

# Get new set with elements that are only in a but not in b
onlyInA = setA.difference(b)

UPDATE
As iurisilvio and mgilson pointed out, this approach only works if a and b do not contain duplicates, and if the order of the elements does not matter.

Solution 3 - Python

You may want this:

a = ["apple", "carrot", "lemon"]
b = ["pineapple", "apple", "tomato"]

new_list = [x for x in a if (x not in b)]

print new_list

Solution 4 - Python

Would this work for you?

a = ["apple", "carrot", "lemon"]
b = ["pineapple", "apple", "tomato"]

new_list = []
for v in a:
    if v not in b:
        new_list.append(v)
        
print new_list

Or, more concisely:

new_list = filter(lambda v: v not in b, a)

Solution 5 - Python

How about using sets (or the built in set since Sets was deprecated in 2.6)?

from sets import Set
a = Set(['apple', 'carrot', 'lemon'])
b = Set(['pineapple','apple','tomato'])
new_set =  a.difference(b)
print new_set

gives the output

Set(['carrot', 'lemon'])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionElizaView Question on Stackoverflow
Solution 1 - PythonSimeon VisserView Answer on Stackoverflow
Solution 2 - PythonMichael Schlottke-LakemperView Answer on Stackoverflow
Solution 3 - PythonmartinView Answer on Stackoverflow
Solution 4 - PythonAlex WilsonView Answer on Stackoverflow
Solution 5 - PythonStuGreyView Answer on Stackoverflow