Mutable And Immutable… Everything Is Object!

INTRODUCTION

Types and Ids

Source: Cafepy
s1 = "Hello"
s2 = "World"
print(id(s1)) #140626500175984
print(id(s2)) #140626500176176
print(type(s1)) #<class 'str'>
print(type(s2)) #<class 'str'>
s2 = "Hello"
print(id(s2)) #140626500175984

Mutable objects

l1 = [1, 2, 3 , 4]
print(l1, id(l1)) #[1, 2, 3, 4] 140028585700864
l1[0] = (5)
l1.reverse()
print(l1, id(l1)) #[5, 3, 2, 1] 140028585700864

Immutable objects

a = 1
b = 2
print(id(a), a) #9784896 1
print(id(b), b) #9784928 2
a = a + b #or a += b
print(id(a), a) #9784960 3
print(id(b), b) #9784928 2
a = (1, 2)
print(id(a), a) #140343551428032 (1, 2)
a[0] = 3 #TypeError: 'tuple' object does not support item assignment

Python Object Handles

l1 = [1, 2, 3 , 4]
l2 = [1, 2, 3 , 4]
s1 = "joe"
s2 = "joe"
print(l1, id(l1)) #[1, 2, 3, 4] 139837454892544
print(l2, id(l2)) #[1, 2, 3, 4] 139837454260352
print(s1, id(s1)) #joe 140245909489648
print(s2, id(s2)) #joe 140245909489648
l1[3] = 5
l1.reverse()
print(l1, id(l1)) #[5, 3, 2, 1] 139837454892544
print(l2, id(l2)) #[1, 2, 3, 4] 139837454260352

Arguments Passed To Functions

def mod(a)
a = 2
a = 0
print(a) #0
mod(a)
print(a) # 0
def mod(l)
l.append(5)
l = [1, 2, 3, 4]
print(l) #[1, 2, 3, 4]
mod(l)
print(l) #[1, 2, 3, 4, 5]

--

--

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