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]
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 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.
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.
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]
.
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