0
1

Python 'and' と '&' の違い

Posted at

‘and’の仕様

左辺が真なら右辺を返し、左辺が偽なら左辺を返す。左辺が偽の時は、右辺を評価しない。(短絡評価)これにより、パフォーマンスの向上やエラーの回避ができる。

# 凡例
0 and 1
1 and 1
1 and 0
1 and 2  # 出力:上から順に0,1,0,2

# エラー回避の例
lst = []
result = lst and lst[0]  # []は'False'扱いなので、andの左辺が処理されて、[]が出力される

‘&’の仕様

‘&’はビットごとのAND演算子である。整数やブール値のビット、numpy配列の各要素に対して、ANDを適用する。

# 0bは2ビットを表す接頭辞
x = 0b1101  # 13
y = 0b1011  # 11

result = x & y
print(bin(result))  # 出力: 0b1001 (9)

# numpy配列に対する演算
a = np.array([0b01, 0b00, 0b11])
b = np.array([0b01, 0b01, 0b01])

result = a & b
print(result)  # 出力: [1 0 1]
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1