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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With