I have two lists in Python, like these:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
I need to create a third list with items from the first list which aren't present in the second one. From the example I have to get:
temp3 = ['Three', 'Four']
Are there any fast ways without cycles and checking?
Beware that
where you might expect/want it to equal
set([1, 3])
. If you do wantset([1, 3])
as your answer, you'll need to useset([1, 2]).symmetric_difference(set([2, 3]))
.i'll toss in since none of the present solutions yield a tuple:
alternatively:
Like the other non-tuple yielding answers in this direction, it preserves order
Let's say we have two lists
we can see from the above two lists that items 1, 3, 5 exist in list2 and items 7, 9 do not. On the other hand, items 1, 3, 5 exist in list1 and items 2, 4 do not.
What is the best solution to return a new list containing items 7, 9 and 2, 4?
All answers above find the solution, now whats the most optimal?
versus
Using timeit we can see the results
returns
I wanted something that would take two lists and could do what
diff
inbash
does. Since this question pops up first when you search for "python diff two lists" and is not very specific, I will post what I came up with.Using
SequenceMather
fromdifflib
you can compare two lists likediff
does. None of the other answers will tell you the position where the difference occurs, but this one does. Some answers give the difference in only one direction. Some reorder the elements. Some don't handle duplicates. But this solution gives you a true difference between two lists:This outputs:
Of course, if your application makes the same assumptions the other answers make, you will benefit from them the most. But if you are looking for a true
diff
functionality, then this is the only way to go.For example, none of the other answers could handle:
But this one does:
Here are a few simple, order-preserving ways of diffing two lists of strings.
Code
An unusual approach using
pathlib
:This assumes both lists contain strings with equivalent beginnings. See the docs for more details. Note, it is not particularly fast compared to set operations.
A straight-forward implementation using
itertools.zip_longest
: