Python provides several built-in data types that define the kind of value a variable can hold.
These data types can be broadly categorized into Mutable and Immutable types based on whether their values can be changed after creation.
🔹 Built-in Data Types in Python
| Category | Data Types | Description |
|---|---|---|
| Numeric | int, float, complex | Used for numeric values like integers, decimals, and complex numbers. |
| Sequence | str, list, tuple, range | Ordered collections of items. |
| Set | set, frozenset | Unordered collections of unique items. |
| Mapping | dict | Collection of key-value pairs. |
| Boolean | bool | Represents True or False. |
| Binary | bytes, bytearray, memoryview | Used to handle binary data. |
| None Type | NoneType | Represents the absence of a value (None). |
🔹 Mutable vs Immutable Data Types
| Type | Description | Examples |
|---|---|---|
| Mutable | Can be changed after creation (modifications like adding, updating, or deleting elements are allowed). | list, dict, set, bytearray |
| Immutable | Cannot be changed once created (any modification creates a new object). | int, float, bool, str, tuple, frozenset, bytes |
🧩 Example 1: Mutable Data Type (List)
my_list = [1, 2, 3]
print("Before:", my_list)
my_list.append(4)
print("After:", my_list)Output:
Before: [1, 2, 3]
After: [1, 2, 3, 4](The same list object is modified — hence mutable.)
🧩 Example 2: Immutable Data Type (String)
my_str = "Hello"
print("Before:", my_str)
my_str = my_str + " World"
print("After:", my_str)Output:
Before: Hello
After: Hello World(A new string object is created — hence immutable.)
🧩 Example 3: Checking Mutability Using id()
x = 10
print("Before:", id(x))
x += 5
print("After:", id(x))Output:
Before: 140705237854448
After: 140705237854768(The object ID changed — integers are immutable.)
🧩 Example 4: Mutable Dictionary
person = {"name": "Dheeraj", "age": 24}
print("Before:", person)
person["age"] = 25
print("After:", person)Output:
Before: {'name': 'Dheeraj', 'age': 24}
After: {'name': 'Dheeraj', 'age': 25}(Same dictionary object is modified — mutable.)
🔹 In Summary
- Mutable Data Types → Can be changed after creation (
list,dict,set). - Immutable Data Types → Cannot be changed once created (
int,str,tuple). - Python internally creates new objects when an immutable value is modified.
- Understanding mutability is crucial for memory management, hashing, and performance optimization.
