Dynamic Variables
Overview
Variables in Python act differently than in C or Java. Instead of creating a 'box' in memory and putting a value inside it, Python variables are simply 'labels' or 'tags' pointing to an object in memory. Because Python is dynamically typed, a variable can point to an integer on one line, and a string on the next. You do not need to declare a variable's type before using it; the interpreter infers the type at runtime based on the assigned object.
Syntax
# Creating variables requires no type declaration
age = 25 # Points to an integer object
age = "Twenty Five" # Now points to a string object (perfectly valid!)
# Multiple assignment in a single line
x, y, z = 1, 2, 3
name, is_admin = "Alice", True
# Variables pointing to the same object
a = [1, 2, 3]
b = a # 'b' now points to the exact same list as 'a'
b.append(4)
print(a) # [1, 2, 3, 4] -> Both changed because they share the same object!Common Pitfalls
- Accidentally overwriting built-in functions by using them as variable names (e.g.,
list = [1, 2], which breaks thelist()function globally). - Assuming assignment copies data.
list_b = list_adoes NOT copy the list; it only copies the reference pointer.
Interview Questions
Variables in Python do not store data directly; they store the memory address of an object. When you assign one variable to another, both point to the exact same object in memory.
Real-World Example
Swapping two variables efficiently without needing a temporary placeholder variable.
player_one_score = 1500
player_two_score = 3200
# In other languages, you need a 'temp' variable.
# Python allows elegant tuple packing and unpacking:
player_one_score, player_two_score = player_two_score, player_one_score
print(player_one_score) # 3200Check Your Knowledge
Test your understanding of Dynamic Variables with these quick questions.