Mutable, Immutable… everything is object!

Id and type

import sys
class empty:
pass
def empty_method():
pass
a_list = [2, 4, 6]
a_tuple = (1, 3)
a_dict = {'Object': 'Yes'}
objects = (a_list, a_tuple, a_dict, sys, 'holberton', 3.1416)
for object in objects:

print('{} with id: {}'.format(type(object), id(object)))
<class 'list'> with id: 140683615619080<class 'tuple'> with id: 140683615620552<class 'dict'> with id: 140683616388936<class 'module'> with id: 140683616805096<class 'str'> with id: 140683615618672<class 'float'> with id: 140683616829560

Python variable handling

int a = 1 --> Box a now contains the integer 1.a = 2 --> Box a now contains number 2 instead of 1
a = b --> b is a second box, with a copy of number 2

Identifier = object

a = 2
b = a
print (id(a))
print (id(b))
1010512010105120

Mutable vs Inmutable

Immutable objects example

x = 789
y = x
print ("x == y -> {}".format(x == y))
print ("x is y -> {}".format(x is y))
print ("id of x before change: {}".format(id(x)))
print ("id of y before change: {}".format(id(y)))
x = 900
print ("x == y -> {}".format(x == y))
print ("x is y -> {}".format(x is y))
print ("id of x after change: {}".format(id(x)))
print ("id of y after change: {}".format(id(y)))
x == y -> True
x is y -> True
id of x before change: 139729799026736
id of y before change: 139729799026736
--------------------------------------------------------------------x == y -> False
x is y -> False
id of x after change: 140150723856400
id of y after change: 139729799026736

you should know… NSMALLPOSINTS and NSMALLNEGINTS

Mutable objects example

list = [10, 20, 33, 40]
print("List before: {}".format(list))
print("id before: {}".format(id(list)))
list[2] = 30print("List after: {}".format(list))
print("id after: {}".format(id(list)))
List before: [10, 20, 33, 40]id before: 140720144087048--------------------------------------------------------------------List after: [10, 20, 30, 40]id after: 140720144087048

Caution!: Immutability Exception

Tup_list = ([9, 3, 10], 7, “Holberton”)
Tup_list = ([9, 3, 10], 7, "Holberton")
print("tuple before {}".format(Tup_list))
Tup_list[0][1] = 5
print("tuple after {}".format(Tup_list))
tuple before ([9, 3, 10], 7, 'Holberton')----------------------------------------------------------------------------------tuple after ([9, 5, 10], 7, 'Holberton')

Why does it matter and how differently does Python treat mutable and immutable objects?

How arguments are passed to functions and what does that imply for mutable and immutable objects?

Recommended for you!

--

--

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