Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between mutable and immutable in python?
Python defines variety of data types of objects. These objects are stored in memory and object mutability depends upon the type. Mutable objects like Lists and Dictionaries can change their content without changing their identity. Immutable objects like Integers, Floats, Strings, and Tuples cannot be modified after creation.
Mutable Objects - Lists
Lists are ordered collections that can be modified after creation. You can change individual elements, add new items, or remove existing ones ?
# Creating a list of numbers
numbers = [1, 2, 3, 4, 5]
print("Original list:", numbers)
# Modifying an element
numbers[0] = 'a'
print("Modified list:", numbers)
# Adding an element
numbers.append(6)
print("After append:", numbers)
Original list: [1, 2, 3, 4, 5] Modified list: ['a', 2, 3, 4, 5] After append: ['a', 2, 3, 4, 5, 6]
Immutable Objects - Tuples
Tuples are ordered collections that cannot be changed after creation. They are written with parentheses and separated by commas ?
# Creating a tuple of numbers
numbers_tuple = (10, 20, 30)
print("Original tuple:", numbers_tuple)
print("Type:", type(numbers_tuple))
Original tuple: (10, 20, 30) Type: <class 'tuple'>
Attempting to Modify a Tuple
When you try to modify a tuple, Python raises a TypeError ?
numbers_tuple = (10, 20, 30)
try:
numbers_tuple[0] = 50
except TypeError as e:
print("Error:", e)
Error: 'tuple' object does not support item assignment
Key Differences
| Aspect | Mutable (List) | Immutable (Tuple) |
|---|---|---|
| Modification | Can be changed | Cannot be changed |
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Performance | Slower | Faster |
| Use Case | Dynamic data | Fixed data |
String Immutability Example
Strings are also immutable in Python. When you "modify" a string, Python creates a new string object ?
text = "Hello"
print("Original:", text)
print("ID:", id(text))
# This creates a new string object
text = text + " World"
print("Modified:", text)
print("New ID:", id(text))
Original: Hello ID: 140712345678912 Modified: Hello World New ID: 140712345679040
Conclusion
Mutable objects like lists can be modified in-place, making them suitable for dynamic data. Immutable objects like tuples and strings cannot be changed after creation, providing data integrity and better performance for fixed data.
