logo

Python の != と is not 演算子の違い

この記事では、次のことを見ていきます。 != (等しくない) 演算子。 Pythonで != と定義されている 等しくない オペレーター。戻ります 真実 どちらかの側のオペランドが互いに等しくない場合、戻り値 間違い それらが等しい場合。一方 ではありません 演算子は、2 つのオブジェクトの id() が同じかどうかをチェックします。同じ場合は返されます 間違い 同じでない場合は返されます 真実。 そして ではありません 演算子は、どちらかの側のオペランドが互いに等しくない場合は True を返し、等しい場合は false を返します。

概念を 1 つずつ理解してみましょう。

例 1:



Python3




a>=> 10> b>=> 10> > print>(a>is> not> b)> print>(>id>(a),>id>(b))> > c>=> 'Python'> d>=> 'Python'> print>(c>is> not> d)> print>(>id>(c),>id>(d))> > e>=> [>1>,>2>,>3>,>4>]> f>=> [>1>,>2>,>3>,>4>]> print>(e>is> not> f)> print>(>id>(e),>id>(f))>

>

>

出力:

False 140733278626480 140733278626480 False 2693154698864 2693154698864 True 2693232342792 2693232342600>

説明:

  1. 最初の整数データでは、変数 a、b の両方が同じデータ 10 を参照しているため、出力は false でした。
  2. 2 番目の文字列データでは、変数 c と d の両方が同じデータ Python を参照しているため、出力は false になりました。
  3. 3 番目のリスト データでは、変数 e、f のメモリ アドレスが異なるため、出力は true になりました。(両方の変数のデータが同じであっても)

例 2:

!= と定義されている 等しくない オペレーター。戻ります 真実 どちらかの側のオペランドが互いに等しくない場合、戻り値 間違い それらが等しい場合。

Python3




# Python3 code to> # illustrate the> # difference between> # != and is operator> > a>=> 10> b>=> 10> print>(a !>=> b)> print>(>id>(a),>id>(b))> > c>=> 'Python'> d>=> 'Python'> print>(c !>=> d)> print>(>id>(c),>id>(d))> > e>=> [>1>,>2>,>3>,>4>]> f>=>[>1>,>2>,>3>,>4>]> print>(e !>=> f)> print>(>id>(e),>id>(f))>

文字列をjsonオブジェクトに変換
>

>

出力:

False 140733278626480 140733278626480 False 2693154698864 2693154698864 False 2693232369224 2693232341064>

例 3:

!= 演算子は 2 つのオブジェクトの値または同等性を比較しますが、Python は ではありません 演算子は、2 つの変数がメモリ内の同じオブジェクトを指しているかどうかをチェックします。

Python3




# Python3 code to> # illustrate the> # difference between> # != and is not operator> # [] is an empty list> list1>=> []> list2>=> []> list3>=> list1> > #First if> if> (list1 !>=> list2):> >print>(>' First if Condition True'>)> else>:> >print>(>'First else Condition False'>)> > #Second if> if> (list1>is> not> list2):> >print>(>'Second if Condition True'>)> else>:> >print>(>'Second else Condition False'>)> > #Third if> if> (list1>is> not> list3):> >print>(>'Third if Condition True'>)> else>:> >print>(>'Third else Condition False'>)> > list3>=> list3>+> list2> > #Fourth if> if> (list1>is> not> list3):> >print>(>'Fourth if Condition True'>)> else>:> >print>(>'Fourth else Condition False'>)>

>

>

出力:

First else Condition False Second if Condition True Third else Condition False Fourth if Condition True>

説明:

  1. の出力 まずもし list1 と list2 は両方とも空のリストであるため、条件は False です。
  2. 2 番目は、2 つの空のリストが異なるメモリ位置にあるため、条件が True を示す場合です。したがって、list1 と list2 は異なるオブジェクトを参照します。オブジェクトの ID を返す Python の id() 関数を使用して確認できます。
  3. の出力 3番目の場合 list1 と list3 の両方が同じオブジェクトを指しているため、条件は False です。
  4. の出力 4番目の場合 2 つのリストを連結すると常に新しいリストが生成されるため、条件は True になります。