Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to XOR two lists in Python? [duplicate]

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.

like image 741
eddiewastaken Avatar asked Dec 27 '17 01:12

eddiewastaken


People also ask

Can you XOR 2 lists Python?

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.

How do you XOR a list 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.

How do you do XOR of two strings in Python?

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.

How do you find the difference between two lists in Python?

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'] .


1 Answers

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.

like image 171
pylang Avatar answered Oct 03 '22 04:10

pylang