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?
We can calculate intersection minus union of lists:
This is another solution:
if you want something more like a changeset... could use Counter
Here is an simple way to distinguish two lists (whatever the contents are), you can get the result as shown below :
Hope this will helpful.
If you run into
TypeError: unhashable type: 'list'
you need to turn lists or sets into tuples, e.g.See also How to compare a list of lists/sets in python?
The difference between two lists (say list1 and list2) can be found using the following simple function.
or
By Using the above function, the difference can be found using
diff(temp2, temp1)
ordiff(temp1, temp2)
. Both will give the result['Four', 'Three']
. You don't have to worry about the order of the list or which list is to be given first.Python doc reference