I am new to programming but I keep learning, and recently I hit the wall so I'm asking for help. Sorry if this was discussed before, but I can't find answer to my problem. I have two lists. And I need to compare them, and in the result to get the objects that DON'T match. For example:
a = [1,2,3,4,5,6]
b = [1,2,3,4,5,6,7,8,9]
result = [7,8,9].
And I only seem to find code and examples that return matches. Which I don't need.
Lists are in file notepad file.txt for you folks to keep in mind if you this helps you to help me. :)
We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.
difference() to get the difference between two lists. Use set() to convert both lists into sets. Use set. difference(s) where set is the first set and s is the second set to get the difference between both sets.
The cmp() function is a built-in method in Python used to compare the elements of two lists. The function is also used to compare two elements and return a value based on the arguments passed. This value can be 1, 0 or -1.
To get the symmetric difference between two lists in Python: Convert the lists to sets. Use the built-in symmetric_difference() function of sets to get the symmetric difference. Convert the result back to a list.
You can convert the lists to sets and run the usual set operations such as difference or symmetric difference. For example, set(b) - set(a)
evaluates to set([7, 8, 9])
.
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