Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove list from list in Python [duplicate]

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.

like image 481
Eliza Avatar asked Jul 11 '12 14:07

Eliza


People also ask

Does convert a list to a set remove duplicates Python?

When you convert a list into a set, all the duplicates will be removed. The set can then be converted back into a list with list() . The drawback of this method is that the use of set() also changes the original list order, which is not restored after it is converted back into a list.


2 Answers

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.

like image 117
Simeon Visser Avatar answered Sep 21 '22 15:09

Simeon Visser


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.

like image 27
Michael Schlottke-Lakemper Avatar answered Sep 21 '22 15:09

Michael Schlottke-Lakemper