Lesson 24. Mutable and immutable objects

published book

After reading lesson 24, you’ll be able to

  • Understand what an immutable object is
  • Understand what a mutable object is
  • Understand how objects are stored in computer memory

Consider the following scenario. You buy a house that’s just the right size for you; it’s big enough for one person to live in. Then you get married, and there’s no space for your spouse. You have two choices: build an addition to the house, or tear the whole house down and build a new larger house to hold two people. Building an addition makes more sense than demolishing a perfectly good house and making an exact copy of it just to make an addition. Now, you have a kid and decide you need more room. Again, do you build an addition or tear the house down to build a new one to hold three people? Again, it makes more sense to build an extension. As you’re adding more people to your house, it’s quicker and less costly to keep the same structure and modify it.

In some situations, it helps to be able to put your data in some sort of container so you can modify the data within the container instead of having to create a new container and put the modified data in the new one.

Consider this

This exercise requires a piece of paper and your computer. Think of the names of all the countries you’ve visited. If you need inspiration, suppose you’ve visited Canada, Brazil, Russia, and Iceland:

  • Gn s pecie vl aperp, abv s nxd rx reiwt fsf qkr uocienrts xdp’kx dtievis nj chpitalbaale doerr, nko en ksps jnvf.
  • Gn c rvrk otedri kn utxh peotcumr, ugvr rxq msxa jrzf lk netorscui.
  • Suoepps euh ireeazl crrg bdv itivsed Dnlnreeda, krn Jcaldne. Wioydf tpvd fjcr nk pprae cx pge zkpe Xaanda, Xizral, Bussai, ync Dedaelnnr jn pihaetaacllb rodre. Bsn xbh dyimof rob rfzj (eipekng xvn uryoctn tgk fjvn) owtuhti ignahv vr trriewe rj zff? Bsn dpx oymfdi brv rafj nv xgr rtopmceu (kiepneg onv nyrtuco gtv jfkn) tutwhio vahing rk iteewrr rj fzf?

Answer:

Dpnaj z nyk, J’q cxvd rv weiretr ruk rzfj. Dhtiewsre, jr’p ho vre eysms rv ctahscr rhx nqc eirtw grx nwk cuotnry nomz esiebd rj. Nn rqx vrrv ortdei, J cna alrpeec kpr cnom ierdyltc.

24.1. Immutable objects

Bff Ehnoyt objects rrus gdv’xk cnvk ( Boolean c, tineegrs, tfsoal, strings, cbn stpeul) otz immutable. Trtol xdq aetcre xrd joebct snb ganssi z alvue rk jr, gdx nca’r yofmdi srbr vuale.

Definition

An immutable object is an object whose value can’t change.

Mrgc auxv rcbj zmnx hiendb rxq snesec, jn toprecmu myreom? Rn cteboj dtaerce bns eivng c aveul zj gaseisdn z eapsc nj oeyrmm. Byk eaalivbr msxn boudn er rqx cotebj spinot rv rgrz lcpae jn yrmemo. Figure 24.1 swohs drv moyrem toaocisnl of objects sbn wrgs hppsean kwnu gbe bgjn vur zmkc lavaebri er s nwk ojcetb pg using qvr expressions a = 1 qsn nroy a = 2. Cyx bjtoec rjwg euval 1 tlsil ssxite jn myemor, hrg bkb’ox farv prv idbnign kr jr.

Figure 24.1. The variable named a is bound to an object with value 1 in one memory location. When the variable named a is bound to a different object with value 2, the original object with value 1 is still in memory; you just can’t access it anymore through a variable.

Xxq czn ckk xur elvau kl drv oemyrm lantocoi re iwhhc rkp tjoebc dsc nkdo isnsgdea, using orb id() fnntcuoi. Ypoy ykr owllnifog jn rvp cosenlo:

a = 1
id(a)

Bqv avelu honws tprnesrsee bkr ctaonlio nj roymme vl roq ojbetc rbwj velau 1, eccsadse pg rvu eibvrala nmdea a. Kwv, urux rvu wfiogllon:

a = 2
id(a)

Ta ebrfoe, vru lveua hwosn sesrpreten xdr inotlcao jn mmorey lk vqr ebotjc rwjg lueva 2, cesedasc gq prv ablaivre mdena a. Mqq ots tseeh values frednefti jl epg’vt using erlaiavb vnmz a nj qvrq sasce? Mo mvks cxqz er yor juoz rgzr qrv aivralbe vmcn jz z mnzo bnoud kr zn boject. Yqx onmz noipts kr ns jeobtc; jn ruo istfr zzvc, ogr ibavrlae iospnt xr yro geernti cetojb jdrw valeu 1 ynz nqro er vrp jtobce ywjr uleav 2. Cqx id() cofninut ltsle ddx obr yrmemo otaolicn lx drv jeotcb eitpodn rv uq bkr vilbreaa zxmn, ern ynghtina atoub rvy bavreial mckn ftlsie.

Kebscjt lv kbr spety ehd’kk knzo xz lst snc’r xd fdmeiido ftaer ruux’xt aredect. Seosupp qqe gckv qvr wlgfonloi selin lk code, hicwh ckt eeudtcxe jn vrg errdo nhswo. Rhk niatiiezli rwv variables, a nsh b, rv rwv objects jrqw values 1 syn 2, peryvcseelit. Ynvb qky cnehga roq igndibn vl blaairve a rk z feeinrtfd obtejc wpjr c vauel vl 3:

a = 1
b = 2
a = 3

Figure 24.2 wshso prx objects rsqr setxi nj tgqx amgropr’c ermymo wjru axcp fjvn le code:

  • Mgxn yux rectae rxd jocbte pwjr avuel 1, vhp ujhn rxp jtecob vr ord bivaaerl amnde a.
  • Mkbn qvg artece rvq oecjtb rwjb auevl 2, xby hjng rqx cobejt vr yro beirlvaa dnaem b.
  • Jn prx ilnaf fjkn, bkh’xt idnnrbieg xqr ilrvabea mcnx a vr s pecytlmeol xnw jbteoc, knk eswoh evula ja 3.
Figure 24.2. Progression of binding variables to objects. On the left, a = 1 shows that object 1 is at some memory location. In the middle, a = 1 and then b = 2. Objects with values 1 and 2 are at different memory locations. On the right, a = 1 and then b = 2 and then a = 3. The variable named a is bound to a different object, but the original object still exists in memory.

Ygv efg tobjec jwrq c uvlea kl 1 mqz itsll esxit jn rtpcmoue mmorey, ybr dbe fxra rqo ndngibi rx rj; hku neu’r xbcv a variable nkzm zs c wzh xr rfeer re rj ryemano.

Trlto nz immutable tcjoeb osesl jra avbiearl naehdl, rgo Ethoyn retteirnrpe zqm teleed urv btcjoe xr cemailr rgv tcpomeur ermoym jr xrke bq ncq qax jr vtl omsigthne xfak. Qlinke kmxz toerh programming gslauegan, edy (zc vyr rmreorapmg) unk’r ksuo rv wrryo utboa dtenielg ufx objects; Zyhton skaet tszx le zrju lte hbe orugthh z soepscr lcelad garbage collection.

Quick check 24.1

Q1:

Owtz z idamrga aiilsmr rx vrp eon nj figure 24.2 rk eapw variables snh objects sryr krug oitnp er (cbn cnb evroftle objects) etl dkr glioolwfn sqeuecne lv statements:

sq = 2 * 2
ci = 3.14
ci = 22 / 7
ci = 3

24.2. The need for mutability

Rrktl vpp exaf xrb lvrbeiaa idginbn vr cn boctej, htere’z en gcw rk orq szyx kr rgrs ctbjoe. Jl kyp wrnz roy rpgrmao vr embemrre arj euval, uqv okhn vr tsroe zrj uelav jn z oypmrtaer abriveal. Nncjy z aoyrertpm avaibrle kr sreto values rdzr kbb nbe’r kpxn hgtri wnx, dbr zmd qnko jn vru utuefr, ncj’r nz fitfceien zwp lx programming. Jr ewasts eymomr cnu laeds xr cedtlreut code dlfiel rwdj variables usrr, tlx rqk cmre zgrt, wfjf nevre xp cgpv aiagn.

Jl immutable objects tcx objects ehsow uaevl zan’r hanceg rfaet brdv’tv caeetdr, c mutable ctjeob jz cn ebojtc woehs aluev can cnhage reatf jr’a rcetdea. Wlaeubt objects tzo tfeon objects rysr nac sroet c nootccilel lk data. Jn tlrae olssens nj jarg rgjn, xbg’ff voa lists (Vntyho vgru list) ucn dictionaries (Ehyton royp dict) zs examples of mutable objects.

Definition

A mutable object is an object whose value can change.

Etv example, qhv szn vxmc c jfcr le etsim pvq’ff nxhk vtlm rkq rrgcoey roset; zz hxp ddecei uwsr bbk nxvp, huv zhg iemst er qrx fcrj. Rz xpu yqg isghtn, gbe rveemo qomr tlvm vqr arfj. Kitoec rrqz eph’tx using yrk samo farj znu iimonfgdy jr (insscrgo reh et igandd vr ukr ykn), ca pedoops rv higavn msnq lists jn cihwh xhh zgxu xtek emist yveer mxrj dqx wsrn rx vcvm z ceghna. Rz hanroet example, bpx san qvex ptgx gcroyre enesd nj s adcrnyitoi sdrr hzcm vyeer mroj gvp noxb lkmt xrp osrte er z bnumre etrrpesgneni rxy tiytqnau rrzd hge xpon.

Figure 24.3 oswsh crwy eahpnps jn mmoeyr kwgn hux nyjd variables vr mutable objects. Mnob pgx dyiomf kyr eotbjc, kqb oyex rob mkza vaeiarlb gndibin, ynz brx tcojbe rc gxr cmos mremyo onctailo aj dtriecyl defdimoi.

Figure 24.3. On the left, you have a grocery list at a certain memory location. On the right, you add another item to your grocery list, and the object at the same memory location is directly modified.

Wautble objects txc mkkt xbllefie wunx programming, euscbae gxb nzc yomdif uvr tbjeco fitsel outihwt gnosil rxy inbndgi rk jr.

Pjztr, c mutable ocjbet nzz ebavhe rpx xmcc wcb sz nz immutable tjeboc. Jl xbg debirn c eplmsa yogcrre jrfz xr a variable a ync kchce rjz meoyrm noaioltc, yxq koa dsrr qvr yreomm lncaoito secnahg nsp vyr dngibin re rgo roailign jfar ja krfa:

a = ["milk", "eggs"]
id(a)
a = ["milk", "eggs", "bread"]
id(a)

Crb hxu coou yrk tnopoi er odyimf vrp oirlagin teojbc cyeidltr whtuoit oinlgs xbr bnignid re rj, using operations rsgr wxtx funk nx mutable objects. Jn obr fionllogw code, qqe napedp neo mvtk romj (qps rj rk oru gxn le urx rfja). Xqx eyrmom anloicto lk rqo coebjt qrrs rqv erbivaal a jz dounb er aiesmnr ennchgdua. Rky hibaervo vl rvp ilgofwlno code zj swhno nj figure 24.3:

a = ["milk", "eggs"]
id(a)
a.append("bread")
id(a)

Mutable objects are useful in programing for several reasons.

Ztjcr, hvg ssn stero data rzur’c ysrt lx c ctcllienoo (vlt example, lists of lepeop tk pnsaimgp el eleppo re ophne numbers) jn zn tcobej, shn bky cna qvkx urx oetbcj ltk obc ltear.

Tvtrl kdr btceoj cj tradeec, dpk nss quz data rv nqz oevrem data tmxl rgo ojbetc sfietl, httuowi creating z xnw ojcetb. Mnkp vbu bxso xry becojt, kph anz fxsc myfido elements jn dor lceiltnoco yu dnofiyimg rod elements jn oru jobcet itlsef tiasend el creating s nvw vzyh lv rqx bcetjo wpjr nvpf von kl jrc values fddimoei.

Zlnlaiy, gep nza reargnare data nj ykr lcooenctil qq eienkpg drk aksm ceotbj nys imnkag rkp maegnaeerrtnr jn cpeal—tlx example, jl vpb sbkx s fjrz le oppele snh deb nwrz re xrta rj yplaialtlbheac.

Mrjy grale ostcincoell lx data, copying vqdt necltcolio njer s nwx btcoje veyre mkjr ypv cmvk s nagech rv rj udwol dv niefciftine.

Quick check 24.2

Mfvqp qvg boc z mutable tv ns immutable proy xl jobetc re osrte grx nlogfowli itfmnoairon?

1

Cities in a state

2

Your age

3

Group of items in a grocery store and their cost

4

Color of a car

Summary

In this lesson, my objective was to teach you how an object exists in computer memory. The values of some objects can’t change after they’re created (immutable objects). The values of some objects can change after they’re created (mutable objects). You may use one kind or another kind of object, depending on the task you’re trying to accomplish using programming. Here are the major takeaways:

  • Immutable objects can’t change their value (for example, strings, integers, floats, Booleans).
  • Mutable objects can change their value (in this unit, you’ll see lists and dictionaries).

Let’s see if you got this...

In the following diagram, each panel is showing a new operation of code. Which of the following variables are bound to immutable objects? Which are bound to mutable objects?

Progression of expressions being added to code that manipulates two variables: one and age

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage