Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get difference from two lists in Python

Tags:

python

I have two lists, l1 and l2. I need items from l1 which are not in l2.

l1 = [2, 3, 4, 5]
l2 = [0, 1, 2, 3]

I want to get only [4,5] - only new values in l1.

[i for i in l1 if not i in l2 ]

Can I do that without iteration?

like image 562
Pol Avatar asked Mar 14 '11 22:03

Pol


People also ask

How do I find the difference between two lists in Python?

Method 6: Use symmetric_difference to Find the Difference Between Two Lists in Python. The elements that are either in the first set or the second set are returned using the symmetric_difference() technique. The intersection, unlike the shared items of the two sets, is not returned by this technique.

Can you subtract two lists in Python?

Use Numpy to Subtract Two Python Lists One of the methods that numpy provides is the subtract() method. The method takes two numpy array s as input and provides element-wise subtractions between the two lists.


2 Answers

Short answer, yes: list(set(l1) - set(l2)), though this will not keep order.

Long answer, no, since internally the CPU will always iterate. Though if you use set() that iteration will be done highly optimized and will be much faster then your list comprehension (not to mention that checking for membership value in list is much faster with sets then lists).

like image 137
orlp Avatar answered Oct 09 '22 03:10

orlp


You can't do it without iteration. Even if you call a single method, internally that will iterate.

Your approach is fine for a small list, but you could use this approach instead for larger lists:

s2 = set(l2)
result = [i for i in l1 if not i in s2 ]

This will be fast and will also preserve the original order of the elements in l1.

like image 37
Mark Byers Avatar answered Oct 09 '22 04:10

Mark Byers