04 June, 2025

Python Lesson 7: Variables की Hidden Power | Interning और Scope Explained

Python Lesson 7: Variables की Hidden Power | Interning और Scope Explained

Python Lesson 7: Variables की Hidden Power

📌 Variable Interning क्या है?

Python में कुछ values जैसे -5 से 256 तक के integers और छोटे strings को बार-बार नया object बनाने की बजाय memory में cache किया जाता है। इसे Interning कहते हैं।

n1 = 256

n2 = 256

print(n1 is n2)  # True

x1 = 300

x2 = 300

print(x1 is x2)  # False

🔍 Scope Chain और LEGB Rule

Python में variable resolution का order होता है:

  • L: Local
  • E: Enclosing
  • G: Global
  • B: Built-in
def outer():

    x = "Enclosing"

    def inner():

        x = "Local"

        print(x)

    inner()

outer()

⚡ Optimization Tips:

  • Reused values को बार-बार redefine न करें।
  • is identity के लिए है, == value comparison के लिए।
  • Immutable types (जैसे tuple, str) को ज़्यादा use करें।

📌 What is Variable Interning?

Python caches integers between -5 to 256 and some short strings to optimize memory. This is called interning.

n1 = 256

n2 = 256

print(n1 is n2)  # True

x1 = 300

x2 = 300

print(x1 is x2)  # False

🔍 Scope Chain and LEGB Rule

Python resolves variables using the LEGB rule:

  • L: Local
  • E: Enclosing
  • G: Global
  • B: Built-in
def outer():

    x = "Enclosing"

    def inner():

        x = "Local"

        print(x)

    inner()

outer()

⚡ Optimization Tips:

  • Don't recreate commonly used values.
  • Use is for identity, == for value comparison.
  • Prefer immutable types like tuple, str.

No comments:

Post a Comment

thank to you