-1

Could someone please explain why the following does not achieve the desired output.

I have two list: l1 and l2. I want to check if either value is 1 in each list and return this to a 3rd list l3.

Have [1,1,0,0] [0,0,0,1]

Want [1,1,0,1]

I have figured out how to get the desired output with list comprehension:

desired = [1 if i[0]==1 or i[1]==1 else 0 for i in list(zip(l1, l2))]

But I am still not sure why the alternate method gives the wrong output.

l1 = [1,1,0,0]
l2 = [0,0,0,1]
l3 = l1 or l2
print(l3)

OUTPUT: [1, 1, 0, 0]

Also if you reverse the order, l3 = [l2 or l1] you get a different output. Can someone explain?

Thanks

patrick
  • 19
  • 3
  • There are add-ons to Python that allow such vectorized operations. I believe Pandas is one such thing, but I'm not sure. – Ulrich Eckhardt Oct 26 '22 at 06:45
  • The `or` operator returns its left hand or right hand operand, *as is*. The `or` operator does not process operands in any way and doesn't have any special handling if the operands are lists. It simple returns the first list that's truthy, *as is*. – deceze Oct 26 '22 at 06:47
  • 1
    BTW, you can simplify your solution to this: `[a or b for a, b in zip(l1, l2)]`. – deceze Oct 26 '22 at 06:47
  • Functional version: `from operator import or_` `map(or_, l1, l2)` or `list(map(or_, l1, l2))` if you need a list. – deceze Oct 26 '22 at 06:50
  • may be you are looking for `!=` operator – Deepak Tripathi Oct 26 '22 at 07:06

1 Answers1

1

here l3 = l1 or l2 is checking if value of l3 will be l1 if l1 has any value ie l1 is not empty or None, otherwise it will be equal to l2

you can understand this will following example

>>> x= [1]
>>> y = []
>>> z = x or y
>>> z
[1]
>>> z = y or x
>>> z
[1]

Note it is not processing internal element of list, it is just checking that object is not empty or None if not that assign that object otherwise assign other one

sahasrara62
  • 10,069
  • 3
  • 29
  • 44