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?
I am little too late in the game for this but you can do a comparison of performance of some of the above mentioned code with this, two of the fastest contenders are,
I apologize for the elementary level of coding.
Can be done using python XOR operator.
most simple way,
use set().difference(set())
answer is
set([1])
can print as a list,
Here's a
Counter
answer for the simplest case.This is shorter than the one above that does two-way diffs because it only does exactly what the question asks: generate a list of what's in the first list but not the second.
Alternatively, depending on your readability preferences, it makes for a decent one-liner:
Output:
Note that you can remove the
list(...)
call if you are just iterating over it.Because this solution uses counters, it handles quantities properly vs the many set-based answers. For example on this input:
The output is:
The existing solutions all offer either one or the other of:
But so far no solution has both. If you want both, try this:
Performance test
Results:
The method I presented as well as preserving order is also (slightly) faster than the set subtraction because it doesn't require construction of an unnecessary set. The performance difference would be more noticable if the first list is considerably longer than the second and if hashing is expensive. Here's a second test demonstrating this:
Results:
Try this: