-1

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.

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Nagesh HS
  • 95
  • 1
  • 3
  • 14

3 Answers3

1

You may try this,

tuple((i or j) for i,j in zip(row[0], row[1]))

or

>>> num = []
>>> k = []
>>> for i, j in zip(row[0], row[1]):
     k.append(i or j)


>>> num.append(tuple(k))
>>> num
[(1, 1, 1)]
>>> 
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • Avinash Raj and Joydeep thank u, the code is working . If I have multiple element in row then can I use the zip function , like : num = tuple(i or j for i, j in zip(for each in row)) – Nagesh HS Nov 01 '16 at 05:42
0

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.

python2:

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

python3:

num = tuple(i or j for i, j in zip(row[0], row[1]))
joydeep bhattacharjee
  • 1,249
  • 4
  • 16
  • 42
0

The reason why you get (1,1,0) is due to short-circuting, and also due to your code. Let me break it down for you.

First iteration:

num == []
element == (1,1,0)
num or element == (1,1,0)
num == (1,1,0)             # due to assignment to num

Second iteration:

num == (1,1,0)             # value from previous iteration
element == (0,0,1)         # 2nd value of row
num or element == (1,1,0)  # due to Short circuiting
num == (1,1,0)             # due to "assignment" to num, in contrast to appending

So, num ends up with (1,1,0).

Solution

You can do what Avinash Raj showed. Here is another way to do it:

row = [(1,1,0),(0,0,1)]
result = tuple(row[0][i] or row[1][i] for i in range(3))
print(result)

Output:

(1, 1, 1)
Community
  • 1
  • 1
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90