Nagesh HS Nagesh HS - 1 year ago 90
Python Question

Logical OR operation between tuple elements in python

I am trying to do logical OR operation between elements inside tuples.

row = [(1,1,0),(0,0,1)]
num = []
for element in row:
num= (num or element)
print num

I am expecting the output
num = [(1,1,1)]
but I am getting
num = [(1,1,0)]

Please suggest suitable method to perform OR operation between elements.

Answer Source

The logic that you used is not correct as iterates whole tuples and thus gives the first tuple as the output when you run the command. As given by Avinash you will have to iterate over each individual element in the tuples and match them side by side. I will recommend the izip function in itertools if you are using python2 else in python3 simple zip function would suffice.


import itertools
num = tuple(i or j for i, j in itertools.izip(row[0], row[1]))


num = tuple(i or j for i, j in zip(row[0], row[1]))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download