Sometimes, while programming, we have a problem in which we might need to perform certain bitwise operations among list elements. This is an essential utility as we come across bitwise operations many times. Let’s discuss certain ways in which XOR can be performed.
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.
Python
test_list = [ 4 , 6 , 2 , 3 , 8 , 9 ]
print ("The original list is : " + str (test_list))
res = reduce ( lambda x, y: x ^ y, test_list)
print ("The Bitwise XOR of list elements are : " + str (res))
|
Output :
The original list is : [4, 6, 2, 3, 8, 9]
The Bitwise XOR of list elements are : 2
Time Complexity: O(n) where n is the number of elements in the list “test_list”.reduce() + lambda + “^” operator performs n number of operations.
Auxiliary Space: O(1), constant extra space is required
Method #2 : Using reduce() + operator.ixor This task can also be performed using this method. In this the task performed by lambda function in above method is performed using ior function for cumulative XOR operation. Works with Python2 only.
Python
from operator import ixor
test_list = [ 4 , 6 , 2 , 3 , 8 , 9 ]
print ("The original list is : " + str (test_list))
res = reduce (ixor, test_list)
print ("The Bitwise XOR of list elements are : " + str (res))
|
Output :
The original list is : [4, 6, 2, 3, 8, 9]
The Bitwise XOR of list elements are : 2
Time Complexity: O(n), where n is the length of the input list. This is because we’re using reduce() + operator.ixor which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(1), as we’re using constant additional space
Method #3 : Using numpy
This task can also be performed using numpy module which provides the bitwise_xor() function to perform this particular task.
Note: Install numpy module using command “pip install numpy”
Python3
import numpy
test_list = [ 4 , 6 , 2 , 3 , 8 , 9 ]
print ( "The original list is : " + str (test_list))
res = numpy.bitwise_xor. reduce (test_list)
print ( "The Bitwise XOR of list elements are : " + str (res))
|
Output :
The original list is : [4, 6, 2, 3, 8, 9]
The Bitwise XOR of list elements are : 2
Time Complexity: O(n)
Space Complexity: O(1)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
09 Apr, 2023
Like Article
Save Article