Python

Basics

Mutable VS Immutable Objects

#!/usr/bin/env python3 -tt
# ======================
# mutables VS immutables
# ======================
"""
Mutables Objects: 
 - List
 - Dictionaty
 - Set
Any new label attributed to the object, inside a function of not, will 'refer' to the same object. Therefore, changing the object using any label will modify the same object. Using any label we will see the modification

Immutable objects
 - Strings 
 - Numbers
 - Float
Any new assignment of a label will copy the object itself, and then atribute that label to the new object. Then, if we change the object using one label, the other object will remain the same.

"""

## Mutable objects
## ---------------
# list
l1=[1,2, 'a']
l2=l1
print('l1:', l1)
print('l2:', l2)
l1.append(3)
print('l1:', l1)
print('l2:', l2)
# Example user-defined function: as list is a mutable object, when we pass it to a function, "my_list" is the label used to manipulate it, and it refers to the same object, not a copy used in the local scope of the function.
def list_mainupation(my_list):
	my_list.append('new element')
	return my_list
print(l1)
list_mainupation(l1)
print(l1)
print(l2)
# therefore we dont even need to return the object or to do any atribution
def list_mainupation(my_list):
	my_list.append('new element')
print(l1)
list_mainupation(l1)
print(l1)
print(l2)

## What if we want to make a copy?
# For list
l3 = l1.copy()                  # or l3=l1[:]
print('l3', l3)
print('l1', l1)
list_mainupation(l1)
print('l1', l1)
print('l3', l3)
list_mainupation(l1[:]) ## we pass a copy of the object, not the one that l1 is refering to
print('l1', l1)
print('l3', l3)


## Immutable objects
a=1
b=a
print(a)
print(b)
b+=2
print(a)
print(b)

s1='first'
s2=s1
print('s1:', s1)
print('s2:', s2)
s2+=' second'
print('s1:', s1)
print('s2:', s2)

def new_string(s):
	s+='XXXX'
	return s
print(s1)
new_string(s1)
print(s1)
#but
s1=new_string(s1)
print(s1)
Mutables Objects: 
 - List
 - Dictionaty
 - Set
Any new label attributed to the object, inside a function of not, will 'refer' to the same object. Therefore, changing the object using any label will modify the same object. Using any label we will see the modification

Immutable objects
 - Strings 
 - Numbers
 - Float
Any new assignment of a label will copy the object itself, and then atribute that label to the new object. Then, if we change the object using one label, the other object will remain the same.