Middle
How are variables structured in Python?
sobes.tech AI
Answer from AI
Variables in Python are not containers of data, but rather labels or names that refer to objects in memory.
When you assign a value to a variable, you are not copying that value, but creating a reference to an existing or new object.
Main concepts:
- Variable names: Can contain letters (Latin), digits, and underscores. Cannot start with a digit. Case-sensitive.
- Objects: Everything in Python is an object. Each object has a type, value, and identifier (memory address).
- References: A variable stores a reference to an object's identifier.
Example:
# Create an int object with value 100 and assign its identifier to 'a'
a = 100
# Variable 'b' now references the same int object with value 100
b = a
# Create a new int object with value 200 and assign its identifier to 'a'
a = 200
In this example, after a = 200, the variable a refers to the new object 200, while the variable b still refers to the object 100.
- Dynamic typing: The type of a variable is determined by the type of the object it references and can change during program execution.
# Variable 'x' references an int object
x = 10
# Now variable 'x' references a str object
x = "hello"
-
Garbage collection: When there are no more references to an object, Python automatically frees the memory occupied by that object using a garbage collection mechanism.
-
Immutable vs. Mutable objects:
- Immutable: Numbers, strings, tuples. Attempting to "modify" such an object actually creates a new object.
- Mutable: Lists, dictionaries, sets. Their contents can be changed without creating a new object.
# Immutable str object
s = "world"
# Create a new str object "hello world", 's' now references it
s = "hello " + s
# Mutable list object
l = [1, 2, 3]
# Modify the existing list object
l.append(4)
Thus, variables in Python are flexible and powerful tools for working with data, based on the concept of references to objects.