同一性と等価性
メニューを表示するにはスワイプしてください
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
is を使用する場合と避ける場合
isはNoneなどのシングルトンとの比較で使用;
12345# Checking if the user has entered their phone number user_phone = None if user_phone is None: print("No phone number provided yet")
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}")
- 数値や文字列同士の等価性の判定には
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)
- ブール値には、真偽値チェックを推奨。
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")
1. 空欄に is または == を入力してください:
2. **「値がない」**ことをテストする正しい方法はどれですか?
3. どの記述が推奨されますか?
すべて明確でしたか?
フィードバックありがとうございます!
セクション 2. 章 3
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 2. 章 3