Python Integert Cache Behavior

🚨 𝗣𝘆𝘁𝗵𝗼𝗻 𝗙𝘂𝗻 𝗙𝗮𝗰𝘁 𝗗𝗮𝘆 𝟭𝟮 𝘚𝘰𝘮𝘦𝘵𝘪𝘮𝘦𝘴 𝘪𝘴 𝘣𝘦𝘤𝘰𝘮𝘦𝘴 𝘛𝘳𝘶𝘦… 𝘧𝘰𝘳 𝘯𝘰 𝘰𝘣𝘷𝘪𝘰𝘶𝘴 𝘳𝘦𝘢𝘴𝘰𝘯 𝚊 = 𝟸𝟻𝟼 𝚋 = 𝟸𝟻𝟼 𝚙𝚛𝚒𝚗𝚝(𝚊 𝚒𝚜 𝚋) 𝗢𝘂𝘁𝗽𝘂𝘁: 𝚃𝚛𝚞𝚎 𝗡𝗼𝘄 𝘁𝗿𝘆 𝘁𝗵𝗶𝘀: 𝚊 = 𝟸𝟻𝟽 𝚋 = 𝟸𝟻𝟽 𝚙𝚛𝚒𝚗𝚝(𝚊 𝚒𝚜 𝚋) 𝗢𝘂𝘁𝗽𝘂𝘁: 𝙵𝚊𝚕𝚜𝚎 (…𝘸𝘢𝘪𝘵 𝘸𝘩𝘢𝘵??) 𝗪𝗵𝗮𝘁’𝘀 𝗴𝗼𝗶𝗻𝗴 𝗼𝗻? Python does a hidden optimization called 𝘪𝘯𝘵𝘦𝘨𝘦𝘳 𝘤𝘢𝘤𝘩𝘪𝘯𝘨: Numbers from -5 to 256 are pre-stored in memory So Python reuses the same object That’s why: 𝟸𝟻𝟼 𝚒𝚜 𝟸𝟻𝟼 → 𝚃𝚛𝚞𝚎  𝟸𝟻𝟽 𝚒𝚜 𝟸𝟻𝟽 → 𝙵𝚊𝚕𝚜𝚎 (new objects created) 𝗜𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝗻𝗼𝘁𝗲: This behavior can vary depending on: • Python version • Environment (REPL, script, etc.) So never rely on this in real code 𝗚𝗼𝗹𝗱𝗲𝗻 𝗿𝘂𝗹𝗲: Use == for value comparison Use 𝚒𝚜 only for identity (like None) 𝚒𝚏 𝚡 𝚒𝚜 𝙽𝚘𝚗𝚎:  # 𝚌𝚘𝚛𝚛𝚎𝚌𝚝 𝗣𝘆𝘁𝗵𝗼𝗻 𝗯𝗲 𝗹𝗶𝗸𝗲: “Optimization bhi karunga… confuse bhi karunga” 𝗥𝗲𝗮𝗹-𝘄𝗼𝗿𝗹𝗱 𝗹𝗲𝘀𝘀𝗼𝗻: If you don’t understand 𝚒𝚜 vs ==, bugs will find you 📌 𝗗𝗮𝘆 𝟭𝟯 𝗰𝗼𝗺𝗶𝗻𝗴 𝘁𝗼𝗺𝗼𝗿𝗿𝗼𝘄: 𝘈 𝘰𝘯𝘦-𝘭𝘪𝘯𝘦 𝘭𝘪𝘴𝘵 𝘵𝘩𝘢𝘵 𝘤𝘳𝘦𝘢𝘵𝘦𝘴 𝘢 𝘉𝘐𝘎 𝘩𝘪𝘥𝘥𝘦𝘯 𝘣𝘶𝘨 𝘍𝘰𝘭𝘭𝘰𝘸 𝘧𝘰𝘳 𝘮𝘰𝘳𝘦 “𝘺𝘦𝘩 𝘬𝘺𝘢 𝘤𝘩𝘢𝘭 𝘳𝘢𝘩𝘢 𝘩𝘢𝘪 𝘗𝘺𝘵𝘩𝘰𝘯?” 𝘮𝘰𝘮𝘦𝘯𝘵𝘴 😄 #Python #Programming #Developers #Coding #AI #DataScience #LearnPython

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories