Mutable vs Immutable Objects in Python


''' Example 1 '''
>>> x = "Holberton"
>>> y = "Holberton"
>>> id(x)
>>> id(y)
>>> print(x is y) '''comparing the types'''
''' Example 2 '''
>>> a = 50
>>> type(a)
<class: ‘int’>
>>> b = "Holberton"
>>> type(b)
<class: 'string'>

Mutable and Immutable Objects

x = 10x = y
id(x) == id(y)id(y) == id(10)
x = x + 1
id(x) != id(y)id(x) != id(10)
m = list([1, 2, 3])n = m
id(m) == id(n)
id(m) == id(n)
  • Python handles mutable and immutable objects differently.
  • Immutable are quicker to access than mutable objects.
  • Mutable objects are great to use when you need to change the size of the object, example list, dict etc.. Immutables are used when you need to ensure that the object you made will always stay the same.
  • Immutable objects are fundamentally expensive to “change”, because doing so involves creating a copy. Changing mutable objects is cheap.

Exceptions in immutability..

How objects are passed to Functions

def updateList(list1):
list1 += [10]
n = [5, 6]
print(id(n)) # 140312184155336
print(n) # [5, 6, 10]
print(id(n)) # 140312184155336
def updateNumber(n):
n += 10
b = 5
print(id(b)) # 10055680
updateNumber(b) # 10055680
print(b) # 5




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Cassandra database migration with Cassper

Python Internet Speed With pyspeedtest

Top 10 online SQL editors

LOOPStarter Airdrop Official Announcement

How To Port SSH to iMX6Q Development Board

Scala for Simpltons. Objects and Classes… Get that static garbage out of here.

Redis Stream in action using Java and Spring Data Redis

Elixir and Ecto

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
megha mohan

megha mohan

More from Medium

How to install GDAL in a Python virtual environment

Learning a new programming language with Conway’s Game of Life (Python to C++)

How to use Python frozenset type

Pattern 3 : Fast & Slow pointers