Variables & Data Types in Python

Module 1 • Session 05 • Allocation: 1 Contact Hr

Memory References Dynamic Typing Primitives Mutability

In Python, variables are not named storage containers holding literal values. Instead, **variables are symbolic references (labels)** bound to objects in system memory. Understanding this memory model is crucial for mastering dynamic typing, mutability, and object lifecycle operations.

1. Variable Binding and Memory Allocation

When executing an assignment statement like x = 42, Python performs three steps behind the scenes:

  1. Creates an integer object in heap memory containing value 42.
  2. Creates the variable identifier x in the local namespace.
  3. Binds reference x to the memory address of the integer object.
Memory Inspection: You can retrieve an object's unique memory address using the built-in id() function, and inspect its reference type using type().
a = [1, 2, 3] b = a # Both 'a' and 'b' reference the SAME list object in memory print(f"Address of a: {id(a)}") print(f"Address of b: {id(b)}") print(f"Do a and b share identity? {a is b}") # Modifying the list via 'b' affects 'a' b.append(4) print(f"Value of a: {a}") # Output: [1, 2, 3, 4]

2. Dynamic Typing and Variable Naming Rules

Python is a **dynamically typed** language. Variable declarations require no explicit type annotations, and variable references can be rebound to entirely different data types during execution.

Variable Naming Conventions (PEP 8)

  • Must begin with a letter (a-z, A-Z) or an underscore (_).
  • Can contain digits (0-9), but cannot start with a digit.
  • Case-sensitive (userCount and usercount are distinct identifiers).
  • Use snake_case for multi-word variables and constants in UPPER_SNAKE_CASE.
  • Avoid reserved keywords (such as class, def, import, if).
# Dynamic Rebinding data = 100 # Bound to int print(type(data)) # data = "Python 3.12" # Rebound to str print(type(data)) # # Multiple Assignment Patterns x, y, z = 10, 20, 30 # Tuple unpacking assignment a = b = c = 0 # Chained assignment to single object print(f"x: {x}, y: {y}, z: {z}") print(f"Chained ids: {id(a) == id(b) == id(c)}")

3. Core Built-In Data Types Overview

Python provides several built-in data structures categorized into **primitive types**, **sequences**, **mappings**, and **sets**.

Category Data Type Example Literal Mutability
Numeric int, float, complex 42, 3.14159, 3 + 4j Immutable
Text Sequence str "Hello World" Immutable
Sequence Types list, tuple, range [1, 2, 3], (1, 2, 3), range(5) List: Mutable / Tuple: Immutable
Mapping Type dict {"key": "value"} Mutable
Set Types set, frozenset {1, 2, 3}, frozenset({1, 2}) Set: Mutable / FrozenSet: Immutable
Boolean & Null bool, NoneType True, False, None Immutable

4. Mutability vs Immutability Mechanics

An object is **immutable** if its value cannot be modified in-place after creation. Any state alteration creates a brand-new object at a different memory location. A **mutable** object allows in-place state modifications without altering its memory identity address.

# Immutable String Reassignment Behavior text = "hello" old_id = id(text) text = text + " world" new_id = id(text) print(f"Original String ID : {old_id}") print(f"New String ID : {new_id}") print(f"Are IDs Identical? : {old_id == new_id}") # False (New object allocated) # Mutable List In-Place Modification numbers = [10, 20] list_id_before = id(numbers) numbers.append(30) list_id_after = id(numbers) print(f"List ID Before Append: {list_id_before}") print(f"List ID After Append : {list_id_after}") print(f"Are IDs Identical? : {list_id_before == list_id_after}") # True (Modified in-place)

5. Type Inspection and Type Hints

Python offers type checking capabilities using type() and isinstance(). Type hints (introduced in PEP 484) clarify expected input and return types without enforcing runtime type checks.

# Type Checking: type() vs isinstance() val = True # Standard check (does not handle inheritance chains) print(type(val) == int) # False # Pythonic check (bool inherits from int in Python) print(isinstance(val, int)) # True print(isinstance(val, bool)) # True # Type Annotations Example def calculate_tax(amount: float, tax_rate: float = 0.05) -> float: return amount * tax_rate print(calculate_tax(150.0, 0.08))

🏋️ Try It Yourself: Practice Challenges

Challenge 1: Memory Address Inspector

Write script logic to verify whether two variables assigned to identical integer values share the exact same id() due to Python's integer caching mechanism (-5 to 256).

Challenge 2: Dynamic Type Auditor

Create a function that accepts a list containing mixed data types, iterates over elements, and prints a structured summary displaying each element, its data type name, and its mutability status.

Challenge 3: Immutable Mutator Trap

Demonstrate what happens when you attempt to modify a tuple that contains a nested mutable list inside it.

⚡ Interactive Sandbox (Variable & Data Type Tester)
Console Output:
Click "Run Code" above to execute interactive input scripts...

📝 Knowledge Check Quiz

1. What actually happens when you assign a variable in Python (`x = 10`)?
2. Which of the following data types in Python is MUTABLE?
3. Why does `isinstance(True, int)` evaluate to `True` in Python?
Advertisement
Horizontal Ad Banner Slot (728x90 / Responsive)