Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all the elements that occur in one list from another

Tags:

python

list

Let's say I have two lists, l1 and l2. I want to perform l1 - l2, which returns all elements of l1 not in l2.

I can think of a naive loop approach to doing this, but that is going to be really inefficient. What is a pythonic and efficient way of doing this?

As an example, if I have l1 = [1,2,6,8] and l2 = [2,3,5,8], l1 - l2 should return [1,6]

like image 999
fandom Avatar asked Nov 18 '10 02:11

fandom


People also ask

How do you remove elements from one list to another?

Method #3 : Using remove() remove() can also perform this task but only if the exception of not getting specific elements is handled properly. One can iterate for all the elements of the removed list and remove those elements from the original list.

How do you remove items from a list from one list to another in Python?

How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.

Does the remove method remove all occurrences of an item from a list?

remove() function. list. remove(x) removes the first occurrence of value x from the list, but it fails to remove all occurrences of value x from the list.


1 Answers

Python has a language feature called List Comprehensions that is perfectly suited to making this sort of thing extremely easy. The following statement does exactly what you want and stores the result in l3:

l3 = [x for x in l1 if x not in l2] 

l3 will contain [1, 6].

like image 180
Donut Avatar answered Sep 24 '22 15:09

Donut