29. Python3: Mutable, Immutable... everything is object!

29. Python3: Mutable, Immutable... everything is object!

Python is a versatile programming language that can handle many different data types. However, it's essential to understand the differences between mutable and immutable objects when working with Python. This blog post will explore what these terms mean and why they matter in Python.

ID and Type

Every object in Python has an ID, a unique identifier for that object. The ID of an object never changes during its lifetime. The type of an object refers to the kind of data it holds. Python has many built-in types, such as strings, integers, and lists.

x = 10

print(id(x))  # Output: 140712066747008

print(type(x)) # Output: <class 'int'>


Mutable Objects

Mutable objects are objects that can be changed after they are created. Examples of mutable objects in Python include lists, dictionaries, and sets. When you modify a mutable object, its ID remains the same.

lst = [1, 2, 3]

print(id(lst)) # Output: 140711651000832


lst.append(4)

print(id(lst)) # Output: 140711651000832


Immutable Objects

Immutable objects, on the other hand, cannot be changed after they are created. Examples of immutable objects in Python include integers, strings, and tuples. When you modify an immutable object, a new object is created with a different ID.

s = "hello"

print(id(s)) # Output: 140711651786640


s += " world"

print(id(s)) # Output: 140711651832912


Why Does It Matter and How Does Python Treat Mutable and Immutable Objects?

Understanding mutable and immutable objects is essential because Python treats them differently. Mutable objects can be changed in place, while immutable objects cannot. This can lead to unexpected behavior if you're not careful.

For example, if you have a function that modifies a mutable object and you pass it to the function, the original object will be changed:

def modify_list(lst):

  lst.append(4)

   

my_list = [1, 2, 3]

modify_list(my_list)

print(my_list) # Output: [1, 2, 3, 4]


However, if you have a function that modifies an immutable object and you pass it to the function, a new object will be created and the original object will not be changed:

def modify_string(s):

  s += " world"

   

my_string = "hello"

modify_string(my_string)

print(my_string) # Output: "hello"


How Arguments are Passed to Functions and What Does That Imply for Mutable and Immutable Objects

In Python, arguments are passed to functions by reference. This means that the function receives a reference to the object rather than a copy of the object. This isn't a problem for immutable objects because the function can't modify the object anyway. However, this can lead to unexpected behavior for mutable objects if you're not careful.


要查看或添加评论,请登录

社区洞察

其他会员也浏览了