Khóa học algorithms

Mutable vs Immutable Objects

0 phút đọc

A mutable object can be changed after it's created, and an immutable object can't.

For example, lists are mutable in Python:

int_list = [4][9]

int_list = 1
# int_list is now[1][9]

And tuples are immutable:

int_tuple = (4, 9)

int_tuple = 1
# Raises: TypeError: 'tuple' object does not support item assignment

Strings can be mutable or immutable depending on the language.

Strings are immutable in Python:

test_string = 'mutable?'

test_string[7] = '!'
# Raises: TypeError: 'str' object does not support item assignment

But in some other languages, like Ruby, strings are mutable:

test_string = 'mutable?'

test_string[7] = '!'
# test_string is now 'mutable!'

Mutable objects are nice because you can make changes in-place, without allocating a new object. But be careful—whenever you make an in-place change to an object, all references to that object will now reflect the change.

Được viết bởi

TechMely Team

Gợi ý câu hỏi phỏng vấn


What's the difference between Host objects and Native objects?


Giải thích LINQ to Objects là gì?


In PHP, objects are they passed by value or by reference?

Gợi ý bài viết

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào

Khoá học javascript từ cơ bản đến chuyên sâuYoutube Techmely