I've got two lists, for example:
a = ['hello','world']
b = ['hello','world','im','steve']
If I want to create a third list that only contains elements NOT in both:
c = ['im','steve']
How do I do this if the order of the elements IS important? I know I can use sets but they keep throwing out the order of my lists. I could use ' '.join(list)
to convert them to strings but not sure how to do this operation in that format either.
Python program to perform XOR on two lists Here two lists are containing integer elements to perform Bitwise XOR. Using the zip module to use simultaneous value each from the list. All elements are in Decimal and output is also in Decimal. ” ^ ” is using for 'exclusive or' in python.
Method #1 : Using reduce() + lambda + “^” operator The above functions can be combined to perform this task. We can employ reduce() to accumulate the result of XOR logic specified by the lambda function. Works only with Python2.
If you want to XOR two strings, it means you want to XOR each character of one string with the character of the other string. You should then XOR ord() value of each char or str1 with ord() value of each char of str2.
The difference between two lists (say list1 and list2) can be found using the following simple function. By Using the above function, the difference can be found using diff(temp2, temp1) or diff(temp1, temp2) . Both will give the result ['Four', 'Three'] .
Option 1: set method (recommended)
Sets have a symmetric_difference
method that exclusively return elements from either a
or b
. Order can be preserved with a list comprehension for a concatenated list a + b
.
comp = set(a).symmetric_difference(b)
[x for x in a + b if x in comp]
# ['im', 'steve']
Option 2: pathlib
method
For reference, another way to diff two lists might be with pathlib.Path.relative_to
method:
import pathlib
p = pathlib.Path(*b)
r = p.relative_to(*a)
list(r.parts)
# ['im', 'steve']
Note: b
is the longer list. This option is potentially less efficient than a simple list comprehension.
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