Python Variables and Memory References
After completing this topic, you will understand that in Python, a variable is not a "box that holds a value," but rather a "name tag that points to an object."
Variables are not boxes.
Many textbooks describe variables as "boxes that hold values." However, this is an inaccurate analogy in Python.
a = 10This code does not mean "put 10 into a box named 'a'." Instead, it means:
- An integer object
10is created in memory. - The name
apoints to (references) that object.
a = 10b = a # b also points to the same object, 10
print(id(a)) # 4350114064print(id(b)) # 4350114064 # Same address!print(a is b) # True # It points to the same objectid() returns the memory address of an object. Both a and b are pointing to the same address. It's not copying the value; it's attaching another name tag to the same object.
Reassignment moves the name tag.
a = 10b = aa = 20 # Reassign 'a' to a new value
print(a) # 20print(b) # 10 # 'b' still points to the original objecta = 20 does not mean "change the object 'a' points to to 20." Instead, a new object 20 is created in memory, and the name tag 'a' is moved to point to it. b still points to the original 10.
== vs. is
x = [1, 2, 3]y = [1, 2, 3]
print(x == y) # True # The values are the sameprint(x is y) # False # They are different objects
z = xprint(x is z) # True # They point to the same object| Operator | Comparison Target | Meaning |
|---|---|---|
== | Value | Are the contents the same? |
is | Identity | Are they the same object? (memory address) |
"Two copies of the same book" would be True for == and False for is. If "the same book is held by two people," then both would be True.
Data Types and Conversion
Python's basic data types:
# Numbersinteger = 42 # int (integer)floating = 3.14 # float (floating-point number)
# Stringtext = "μλ
νμΈμ" # str
# Booleanflag = True # bool (True/False)
# None - a special type that represents "no value"result = None
# Type checkingprint(type(42)) # <class 'int'>print(type("hello")) # <class 'str'>Type Conversion
# String to numberage = int("25") # 25price = float("9.99") # 9.99
# Number to stringstr(42) # "42"
# Caution: Error if conversion is not possibleint("hello") # ValueError!Naming Rules
# Good variable names - names that reveal their meaninguser_name = "κΉν"total_score = 95is_active = True
# Bad variable namesx = "κΉν" # Cannot tell what value it holdsa1 = 95 # Meaningless
# Rules# - You can use letters, numbers, and underscores (_)# - Cannot start with a number (2name β Error)# - snake_case is recommended (Python convention)# - Cannot use reserved words (if, for, class, etc.)Python uses snake_case rather than camelCase. Instead of userName, use user_name. This is a recommendation from PEP 8 (the official Python style guide).