Complete Guide to Python Data Types With Memory Model and Code Examples
Introduction:
Python is dynamically typed. That means you do not declare variable types explicitly. The interpreter decides the type at runtime. Understanding data types is not optional. It affects memory usage, performance, and debugging.
In this guide, you will learn:
• Core built in data types
• Mutable vs immutable objects
• Memory behavior
• Type checking
• Common mistakes
• Best practices
Numeric Types
Python has three main numeric types.
int
float
complex
Example:
x = 10
y = 3.14
z = 2 + 3j
int stores whole numbers.
float stores decimal numbers.
complex stores real and imaginary parts.
Memory insight:
Python integers are objects. They are not fixed 32 bit like C. They grow dynamically based on size.
Check type:
type(x)2. Boolean Type
Boolean represents True or False.
is_active = True
Internally True equals 1, False equals 0.
Example:
print(True + True)
Output is 2.
-
String Type
Strings are immutable sequences of Unicode characters.
name = "World"
Immutable means once created, it cannot change.
Wrong idea:
name[0] = "R"
This throws an error.
Correct way:
name = "R" + name[1:]
-
List
Lists are ordered and mutable.
numbers = [1, 2, 3]
numbers.append(4)
Lists allow modification.
Memory note:
Lists store references to objects, not the objects directly.
-
Tuple
Tuples are ordered but immutable.
point = (10, 20)
Why use tuple?
• Faster than list
• Safe from modification
• Good for fixed data
-
Dictionary
Dictionary stores key value pairs.
student = {
"name": "World",
"age": 20
}
Keys must be immutable types.
Access value:
student["name"]
-
Set
Set stores unique elements.
unique_ids = {1, 2, 3}
Duplicate values are removed automatically.
-
Mutable vs Immutable
Immutable types:
int, float, bool, string, tuple
Mutable types:
list, dict, set
Example:
a = 5
b = a
a = 10
b remains 5 because integers are immutable.
Now compare list:
a = [1, 2]
b = a
a.append(3)
b becomes [1, 2, 3] because both reference same object.
Identity vs Equality
Equality checks value.
a == b
Identity checks memory reference.
a is b
Common bug:
a = [1,2]
b = [1,2]a == b is True
a is b is False
Best Practices
• Use tuple for fixed data
• Avoid modifying list while iterating
• Use dictionary for fast lookup
• Use set for uniqueness
• Understand reference behavior
Conclusion
Understanding Python data types improves debugging, performance, and code design. Most beginner bugs come from misunderstanding mutability and references.
Master this before moving to advanced topics like decorators or async programming.

Comments
Post a Comment