Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 同一性と等価性 | ブール値と比較
Pythonのデータ型

book同一性と等価性

メニューを表示するにはスワイプしてください

Pythonにおける同一性等価性の違いについて解説。同一性は、2つの変数がメモリ上の同じオブジェクトを参照しているかどうかを確認し、等価性は2つのオブジェクトが同じ値を持っているかどうかを比較。これらの違いを理解することは、正確な条件分岐、バリデーション、データ処理ロジックの記述に不可欠。

isとは?

  • isオブジェクトの同一性を確認し、2つの変数がメモリ上の同じオブジェクトを指しているかどうかを判定;
  • ==値の等価性を確認し、2つのオブジェクトが同じ内容を持っているかどうかを判定。
12345678
# Comparing two shopping carts in an online store cart_today = ["milk", "bread"] cart_yesterday = ["milk", "bread"] shared_cart = cart_today print(cart_today == cart_yesterday) # True → same items print(cart_today is cart_yesterday) # False → two separate cart objects print(cart_today is shared_cart) # True → both refer to the same cart
copy

is を使用する場合と避ける場合

  • isNone などのシングルトンとの比較で使用;
12345
# Checking if the user has entered their phone number user_phone = None if user_phone is None: print("No phone number provided yet")
copy
  • is not は否定の同一性チェック;
12345
# Checking if the user's age is stored in the system user_age = 64 if user_age is not None: print(f"User age is recorded: {user_age}")
copy
  • 数値や文字列同士の等価性の判定には is を使用しないこと。内部的なキャッシュやインターンの影響で、is が一見正しく動作する場合があるが、実行環境やタイミングによって結果が異なるため信頼できない。等価性の判定には == を使用すること。
123456789101112
# Comparing user IDs and usernames in a system user_id_a = 256 user_id_b = 256 print(user_id_a == user_id_b) # True → same user ID value print(user_id_a is user_id_b) # May appear True, but identity check is unreliable for numbers username_a = "hello" username_b = "he" + "llo" print(username_a == username_b) # True → same text print(username_a is username_b) # Avoid using 'is' for string comparison (implementation detail)
copy
  • ブール値には、真偽値チェックを推奨。
12345
# Checking if dark mode is enabled in user settings dark_mode_enabled = True if dark_mode_enabled: # clearer than: if dark_mode_enabled is True print("Dark mode is ON")
copy

1. 空欄に is または == を入力してください:

2. **「値がない」**ことをテストする正しい方法はどれですか?

3. どの記述が推奨されますか?

question-icon

空欄に is または == を入力してください:

Use to check if two variables point to the same object.
Use
to check if two values have the same contents.

クリックまたはドラッグ`n`ドロップして空欄を埋めてください

question mark

**「値がない」**ことをテストする正しい方法はどれですか?

正しい答えを選んでください

question mark

どの記述が推奨されますか?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 2.  3

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 2.  3
some-alt