Python

Mutability in Python

Click for All Topics

Mutable & Immutable objects in Python

In Python, mutability refers to the ability of an object to be changed after it has been created.                                                    If, an object can change it’s value after being created then it is known as mutable otherwise if it’s unable to change the value then it is immutable.

Mutable Objects:

  • Lists: You can change the contents of a list by adding, removing, or modifying items.

Example –

				
					my_list=[1,2,3,4,5]
print("Original list:",my_list)

my_list.append(6)
print("Original list after add a new element:\n",my_list)

my_list.remove(3)
print("Original list after remove 3 from list:\n",my_list)

# Output -
# Original list: [1, 2, 3, 4, 5]
# Original list after add a new element:
 # [1, 2, 3, 4, 5, 6]
# Original list after remove 3 from list:
 # [1, 2, 4, 5, 6]
				
			
  • Dictionaries: Similar to lists, you can add new key-value pairs to a dictionary, modify values, or delete keys.
				
					my_dict={'a':1,'b':2,'c':3,'d':4}
print("Original Dictionary:",my_dict)

my_dict.update({'e':5})
print("Original Dictionary after add new item:\n",my_dict)

del my_dict['b']
print("Original Dictionary after removing a item from dictinaory:")
print(my_dict)

# Output -
# Original Dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Original Dictionary after add new item:
 # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# Original Dictionary after removing a item from dictinaory:
# {'a': 1, 'c': 3, 'd': 4, 'e': 5}
				
			
  • Sets: While the elements in a set must be immutable, the set itself can have elements added or removed.
				
					my_set={1,2,3,4,5,6}
print("Original set:",my_set)

my_set.add(7)
print("Original set after add new item 7:\n",my_set)

my_set.discard(4)
print("Original set after removing 4 from set:\n",my_set)

# Output -
# Original set: {1, 2, 3, 4, 5, 6}
# Original set after add new item 7:
 # {1, 2, 3, 4, 5, 6, 7}
# Original set after removing 4 from set:
 # {1, 2, 3, 5, 6, 7}
				
			

 

 

Immutable Objects:

 

  • Integers: When you perform operations on an integer, you’re actually creating a new object, not modifying the old one.

Example –

				
					# Original integer
a = 5

# Performing an operation on the integer (creating a new object)
b = a + 3

# Printing the original integer and the new one
print("Original integer:", a)
print("New integer:", b)

# Output -
# Original integer: 5
# New integer: 8
				
			
  • Floats: Like integers, operations on floats yield new objects.

Example –

				
					# Original floating-point number
a = 3.5

# Performing an operation on the floating-point number
# (creating a new object)
b = a * 2

# Printing the original floating-point number and the new one
print("Original float:", a)
print("New float:", b)

# Output -
# Original float: 3.5
# New float: 7.0
				
			
  • Strings: You cannot change a string in place, attempting to do so will result in an error. Instead, you create a new string with the desired changes.

Example –

				
					my_string='edSlash'
print("Original String:",my_string)

my_string[1]='anurag'  # will give an error

# Output -
# Original String: edSlash
# Traceback (most recent call last):
  # File "/home/main.py", line 4, in <module>
    # my_string[1]='anurag'  # will give an error
# TypeError: 'str' object does not support item assignment
				
			
				
					

# Creating a new string 
my_string = 'Hello'
print("Orignal String:",my_string)

new_string = my_string + 'World!'
print("New string:",new_string)

# Output -
# Orignal String: Hello
# New string: HelloWorld!
				
			
  • Tuples: These are like lists in terms of indexing and nesting, but you cannot change a tuple once it’s created.

Example –

				
					my_tuple = (1,2,3,4)
print("Original tuple:",my_tuple)

# try to modify my_tuple 
my_tuple[0]=9   # will give an error

# Output -
# Original tuple: (1, 2, 3, 4)
# Traceback (most recent call last):
  # File "main.py", line 5, in <module>
    # my_tuple[0]=9
# TypeError: 'tuple' object does not support item assignment
				
			

Why Does Mutability Matter?

Understanding mutability is crucial when you’re working with data structures:

  • Efficiency: Mutable objects can be more memory-efficient because you can make changes in place rather than creating new objects.

 

  • Safety: Immutable objects are safe from unintended side-effects, which is particularly useful in multi-threaded environments.

 

  • Predictability: Functions that operate on immutable objects are generally easier to reason about, as they don’t cause side effects outside their scope.