Mutable vs Immutable in Python|python tutorial for beginners 5 [2020]

Published: 09 May 2020
on channel: hwdong
28
0

medium:   / hwdong  
youtube channel hwdong :    / @hwdong  
blog:https://hwdong.net
腾讯课堂高质量编程课程:http://hwdong.ke.qq.com
B站编程课程hw-dong:https://space.bilibili.com/281453312
推特 :  / hwdong  
电报群:https://t.me/hwdong
-----------------------------------------------------------------------------------------
Mutable vs Immutable in Python|python tutorial for beginners 5 [2020]

Every variable in python holds an instance of an object. There are two types of objects in python i.e. Mutable and Immutable objects.

mutable objects can change their state or contents or values and immutable objects can’t change their state or content or values.

Immutable Objects : These are of in-built types like int, float, bool, string, unicode, tuple. In simple words, an immutable object can’t be changed after it is created.
x = 2
y = 2
x is y

x = 3 # didn't change x but define a new varialbe x refer to a new object
print(y) # y refer the old object 2

x= "hello"
y = x
x = 3
print(y)
print(x)

Let's try to modify the element of x.
x[0] = 'A'
TypeError: 'int' object does not support item assignment
Let's try to modify the content of a tuple:
t = (1,2,3)
t[0] = 10
TypeError: 'tuple' object does not support item assignment

But we can change the element of a list:
l = [1,2,3]
l[0] = 10
print(l)
How about this:

a = ([1,2,3],'hwdong')
a[0][2] = 20
print(a)

Although the element of a tuple can't be modified,but the elment of a tuple may be mutable.

mutable Objects : list、set、dict are mutable bulit-in types.
d = dict()
print(d)
d['hello'] = 3.14
print(d)
d['world'] = 'hwdong'
print(d)

d.pop('world',None)
print(d)

set
A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
s= {'hello','world',3.14}
s.add(2)
print(s)
s.remove('world')
print(s)


On this page of the site you can watch the video online Mutable vs Immutable in Python|python tutorial for beginners 5 [2020] with a duration of hours minute second in good quality, which was uploaded by the user hwdong 09 May 2020, share the link with friends and acquaintances, this video has already been watched 28 times on youtube and it was liked by 0 viewers. Enjoy your viewing!