| この記事の要点 |
|
一覧
| 演算子 | 意味 | 例 | 結果 |
|---|---|---|---|
== | 等しい | 1 == 1.0 | True |
!= | 等しくない | "a" != "b" | True |
< <= | より小さい / 以下 | 3 <= 3 | True |
> >= | より大きい / 以上 | 3 > 5 | False |
Python には <>(不等号の古い書き方)はありません。!= を使います。
連鎖比較
x = 5
print(0 <= x < 10) # True 範囲チェックがそのまま書ける
print(1 < 2 < 3 < 4) # True
# 中央の式は 1 回しか評価されない
def f():
print("called")
return 5
print(0 < f() < 10) # called が 1 回だけ出る
# a == b == c は「3 つとも等しい」
print(1 == 1 == 1) # True
print(1 == 1 == 2) # False
== と is の使い分け
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True 中身が同じ
print(a is b) # False 別オブジェクト
x = None
print(x is None) # 正しい書き方
print(x is not None) # 否定は is not(not x is None ではない)
# 小さい int や短い文字列はキャッシュされていて紛らわしい
print(256 is 256) # True になることがある(実装依存)
print(1000 is 1000) # False になることがある
# → 値の比較に is を使わない
is を使ってよいのは None / True / False のような唯一のオブジェクトが決まっているものとの比較だけです。
float の比較
print(0.1 + 0.2 == 0.3) # False 誤差で一致しない
import math
print(math.isclose(0.1 + 0.2, 0.3)) # True
print(math.isclose(1000.0, 1000.1, rel_tol=1e-3)) # True 相対誤差
print(math.isclose(0.0, 1e-12, abs_tol=1e-9)) # True 絶対誤差
# nan は自分自身とも等しくない
nan = float("nan")
print(nan == nan) # False
print(math.isnan(nan)) # True ← 判定はこちら
rel_tol は既定で 1e-09 です。0 との比較だけは相対誤差が効かないので abs_tol を明示してください。
シーケンス・辞書・集合の比較
print([1, 2, 3] == [1, 2, 3]) # True 要素と順序が一致
print([1, 2] < [1, 3]) # True 先頭から辞書順に比較
print([1, 2] < [1, 2, 0]) # True 前半が同じなら短い方が小さい
print((1, 2) == [1, 2]) # False 型が違えば等しくない
print({"a": 1} == {"a": 1}) # True 辞書は順序を問わない
# 辞書に < > は無い(TypeError)
print({1, 2} < {1, 2, 3}) # True 集合の < は「真部分集合」
print({1, 2}.issubset({1, 2})) # True
異なる型どうしの比較
print(1 == 1.0) # True 数値どうしは型が違っても比べられる
print(1 == "1") # False 文字列とは等しくならない(例外にもならない)
# 大小比較は例外になる
# print(1 < "1")
# TypeError: '<' not supported between instances of 'int' and 'str'
# bool は int のサブクラス
print(True == 1, False == 0) # True True
print(True + True) # 2
Python 2 では型が違っても大小比較できましたが、Python 3 では TypeError になります。ソート時に None が混ざって落ちるのは、この仕様が原因であることが多いです。
自作クラスの比較
from functools import total_ordering
@total_ordering
class Ver:
def __init__(self, major, minor):
self.major, self.minor = major, minor
def __eq__(self, other):
return (self.major, self.minor) == (other.major, other.minor)
def __lt__(self, other):
return (self.major, self.minor) < (other.major, other.minor)
print(Ver(1, 2) < Ver(1, 10)) # True
print(Ver(1, 2) >= Ver(1, 2)) # True total_ordering が残りを補う
__eq__ を定義したクラスは既定でハッシュ不可になり set や辞書のキーに使えません。必要なら __hash__ も定義してください。
関連
子ページ
子ページはありません
人気ページ
- 1 Eclipseで「サーバーに追加または除去できるリソースがありません。」の原因と対処法
- 2 tomcat の起動 / 停止ログと catalina.log・catalina.out の違い
- 3 JavaScript で base URL を取得する方法|window.location.origin
- 4 YouTube Data API v3 エラー一覧|403・400・404 の原因と対処
- 5 Laravel エラー一覧|500/Blade/DB 接続/ルーティングの代表エラー
- 6 3Dグラフィックスとは|モデリング/レンダリング/主要ソフトウェア (Blender / Maya)
- 7 Spring Frameworkのアノテーション一覧
- 8 【Spring】@Valueアノテーションとは
- 9 CATALINA_HOME の確認方法 (Linux / Mac)
- 10 【Spring】@Autowiredアノテーションとは
最近更新/作成されたページ
- プロジェクトをTomcatプロジェクトとして認識させる方法 2026-10-07 22:32:50
- MySQLの1366 Incorrect string value|Laravelの文字コード・絵文字エラー 2026-10-07 21:54:03
- curlの証明書ホスト名不一致|旧エラー51・現行60の確認と対処 2026-10-07 21:54:03
- LaravelのMassAssignmentException|fillableの原因と安全な対処 2026-10-07 21:54:03
- Eclipse で Tomcat の起動ログがコンソールに出ない時の確認手順 2026-10-07 21:54:02
- MySQLにおける中央値(Median)の導き方(バージョン8未満) 2026-10-07 13:49:45
- getInputForward 2026-10-07 13:41:15
- JSONから配列に変換 2026-10-07 13:41:15
- ビューから値をモデルに格納しコントローラーで受け取る方法 2026-10-07 13:23:41
- Laravelのテーブル作成と定義変更|マイグレーション・up/down・注意点 2026-10-07 13:23:41
- NumPy 配列に要素を追加する方法 (append / concatenate) 2026-10-07 13:23:41
- MariaDB・MySQLで現在日時を取得する方法|NOW・タイムゾーン・保存型 2026-10-07 13:13:36
- 【django】テンプレートで定数を使用する方法 2026-10-07 13:10:15
- Spring BootにおけるApplication.propertiesの環境依存設定の分割方法 2026-10-07 12:09:35
- Not supported for DML operations【Springエラー】 2026-10-07 11:09:38