0

So I will to apply and element wise AND operation of each element between two lists of ints but only 0 and 1, and return a list. So I dont think all() is applicable here. e.g.

[1, 0, 0] AND [1, 1, 0] => [1, 0, 0]

One way I can use list comprehension

[i * j for i, j in zip(x, y)]

But I wonder if there is a more bitwise way of doing it.

Many thanks.

J_yang
  • 2,672
  • 8
  • 32
  • 61

1 Answers1

4

You can use operator.and_ which essentially performs bitwise and operation, which is generally done by &:

>>> from operator import and_
>>> list(map(and_, [1, 0, 0], [1, 1, 0]))
[1, 0, 0]

Generally list comprehension should be preferred. As with map it is only useful when you have a builtin function, which in this case can obtained from operator, but even then, map approach has to perform another explicit list call, which would be slightly slower, furthermore even with builtin function list comprehension and map are almost identical in performance. Add that to the fact that list comprehension is generally more verbose. So unless you have a requirement to use functional approach, it is better to stick to list comprehension.

Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52