Python Mutable vs Immutable Objects¶
- In Python, data types can be categorized as either mutable or immutable.
- An immutable object can’t be changed after it is created.
- An object that cannot be changed after it’s created is called immutable.
- An object that can be changed after it’s created is called mutable.
| Class | Description | Immutable or Mutable |
|---|---|---|
| set | unordered set of distinct objects | Mutable |
| list | mutable sequence of object | Mutable |
| dictionary | associative mapping | Mutable |
| bool | Boolean value | Immutable |
| int | integer | Immutable |
| float | floating-point number | Immutable |
| tuple | immutable sequence of object | Immutable |
| str | character string | Immutable |
| frozenset | immutable form of set class | Immutable |
| Mutable Objects | Immutable Objects |
|---|---|
| These objects can be modified after they are created. | These objects remain unchanged once created. |
| Usually, they include methods to add, remove, or update elements. | They don’t support any operations to modify, add, or remove elements. |
| Access speed is generally slower compared to immutable objects. | Faster to access compared to mutable objects. |
| Modifying mutable objects is straightforward and efficient. | Modification is either not possible or computationally costly. |
| Examples: Lists, Sets, Dictionaries, etc. | Examples: Tuples, Strings, Frozensets, etc. |
Python Immutable Data Types:¶
- Numbers (int, float, complex): Numeric data types are immutable. When you perform operations that change their value, a new object is created in memory.
In [ ]:
x = 10
y = x # y references the same 10
print("id of x: ",id(x))
print("id of y: ", id(y))
x += 1 # Now x is 11, a new object is created
print("New id of x: ",id(x))
id of x: 10751144 id of y: 10751144 New id of x: 10751176
- Strings: Strings are immutable. You can't change the characters of a string once it's created. When you modify a string, a new string is created.
In [ ]:
my_str = "Intensity"
print("id of my_str: ",id(my_str))
my_str += " Coding" # Creates a new string with "Intensity Coding"
print("New id of my_str: ",id(my_str))
id of my_str: 137843795649776 New id of my_str: 137843795581712
- Tuples: Tuples are also immutable. You can't change their elements after creation.
In [ ]:
my_tuple = (1, 2, 3)
# This is not allowed: my_tuple[0] = 10
Python Mutable Data Types:¶
- Lists: Lists are mutable. You can change, add, or remove elements from a list after creation.
In [ ]:
my_list = [1, 2, 3]
my_list.append(4) # Modifies the list in place
print(my_list)
[1, 2, 3, 4]
- Dictionaries: Dictionaries are mutable. You can modify the key-value pairs in a dictionary.
In [ ]:
my_dict = {'name': 'Raj', 'age': 35}
my_dict['age'] = 31 # Changes the 'age' value
print(my_dict)
{'name': 'Raj', 'age': 31}
- Sets: Sets are mutable. You can add or remove elements from a set.
In [ ]:
my_set = {1, 2, 3}
my_set.add(4) # Modifies the set to include 4
print(my_set)
{1, 2, 3, 4}
Python Collections¶
- There are four collection data types in the Python programming language:
1. List
- Lists are ordered and mutable(changeable) collections of data.
- Allows duplicate members.
- They are created using square brackets
[ ].
In [ ]:
my_list = [1, 2, 3, 4, 5]
2. Tuple
- Tuples are ordered and immutable(unchangeable) collections of data.
- Allows duplicate members.
- They are created using parentheses
( ).
In [ ]:
my_tuple = (1, 2, 3, 4, 5)
3. Set
- Sets are unordered collections of unique elements which is unchangeable and unindexed.
- No duplicate members.
- Set items are unchangeable, but you can remove and/or add items whenever you like.
- They are created using curly braces
{ }or with the set() constructor.
In [ ]:
my_set = {1, 2, 3, 4, 5}
4. Dictionary
- Dictionaries are collections of key-value pairs.
- It is ordered and changeable.
- No duplicate members.
- They are created using curly braces
{ }with key-value pairs.
In [ ]:
my_dict = {"name": "Raj", "age": 35, "city": "Jaipur"}
| Feature | Lists | Tuples | Sets | Dictionaries |
|---|---|---|---|---|
| Constructor | [] or list() |
() or tuple() |
{} or set() |
{} or dict() |
| Ordering | Ordered | Ordered | Unordered | Ordered |
| Indexing | Indexed | Indexed | Not Indexed | Key Value Pair |
| Mutability | Mutable | Immutable | Mutable (Only Adding and Removing) | Mutable |
| Duplicates Allowed | Yes | Yes | No | Yes (Only in values, not in keys) |
| Slicing | Allowed | Allowed | Not Allowed | Not Allowed |