Remove list from list in Python

Remove list from list in 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.

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.

Remove list from list in 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

Leave a Reply

Your email address will not be published. Required fields are marked *