![]() ![]() Functions such as append, extend, and update all modify the list or dictionary they refer to, and can be very useful for keeping track of data or accomplishing a certain programming task. If you think about the functionality of lists and dictionaries, you’ll realize you’ve been taking advantage of their mutability all along, even if you may not have realized it. I will need to define a new string if I want to fix the spelling. Once the string has been defined, its contents cannot be changed. If I then try to modify the string, Python complains: > my_song = "All Too Wall" > my_song = 'e' Traceback (most recent call last): File "", line 1, in TypeError: 'str' object does not support item assignment If I want to change the list by replacing one of the songs, that’s perfectly fine, because lists are mutable: > my_songs = > my_songs = "Champagne Problems" > my_songs īy contrast, suppose I define a string, which is an immutable object, but I accidentally misspell it. Let’s look at a concrete example of the difference between mutability and immutability. ![]() The two types of mutable objects you’ll likely deal with most often when programming in Python are lists and dictionaries. The opposite of a mutable object is an immutable object, whose state cannot be altered after it is initially defined.Įxamples of immutable objects in Python include integers, floats, strings, and tuples. In technical programming terms, a mutable object is an object whose state can be modified after it is defined. In this article, I will present an overview of mutability along with some detailed examples. A faulty understanding or lack of awareness about how mutability works can lead to confusing errors or even seemingly working code that breaks later on. This is an issue, as it is an important concept which affects how a programmer writes and develops code. However, it is often overlooked in trainings focused on data science, statistics, user experience, bioengineering, or any other related field that makes use of code somehow. Understanding object mutability is an important concept that will almost certainly be covered in a computer science class or boot camp. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |