Python | Bitwise OR among List elements
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 this task 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 OR logic specified by the lambda function. Works only with Python2.
Python
test_list = [ 7 , 8 , 9 , 1 , 10 , 7 ]
print ("The original list is : " + str (test_list))
res = reduce ( lambda x, y: x | y, test_list)
print ("The Bitwise OR of list elements are : " + str (res))
|
Output :
The original list is : [7, 8, 9, 1, 10, 7]
The Bitwise OR of list elements are : 15
Time complexity: O(n)
Auxiliary space: O(1)
Method #2: Using reduce() + operator.ior 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 OR operation. Works with Python2 only.
Python
from operator import ior
test_list = [ 7 , 8 , 9 , 1 , 10 , 7 ]
print ("The original list is : " + str (test_list))
res = reduce (ior, test_list)
print ("The Bitwise OR of list elements are : " + str (res))
|
Output :
The original list is : [7, 8, 9, 1, 10, 7]
The Bitwise OR of list elements are : 15
Time complexity: O(n)
Auxiliary space: O(1)
Method #3: Using a loop to perform a bitwise OR among the elements of a list
Python3
test_list = [ 7 , 8 , 9 , 1 , 10 , 7 ]
print ( "The original list is : " + str (test_list))
result = test_list[ 0 ]
for i in range ( 1 , len (test_list)):
result = result | test_list[i]
print ( "The Bitwise OR of list elements are : " + str (result))
|
Output
The original list is : [7, 8, 9, 1, 10, 7]
The Bitwise OR of list elements are : 15
Time complexity: O(n)
Auxiliary space: O(1)
Last Updated :
01 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...