After reading lesson 25, you’ll be able to
- Build Python lists
- Add items, remove items, and modify items in Python lists
- Perform operations on list elements
Mutable data types are types of objects on which you can perform operations, such that the object’s value is modified; the modification is done in place, so to speak, so no copy of the object is made. There’s a need for data types that are mutable, especially when working with large amounts of data; it’s more efficient to modify data stored directly instead of copying it into a new object with every operation.
Instead of creating new objects, it’s sometimes useful to reuse an object and modify its value. This is especially true when you have an object that represents an ordered collection of other objects. Most programming languages have a data type to represent this type of ordered collection that you can mutate. In Python, this is called a list. A list is a new type of object that you haven’t seen before. It represents an ordered collection of other object types. Among many others, you can have lists of numbers, lists of strings, or even a list of a mix of object types.
Ulnrx pkg’ff njlh yrrs qdx uonx rk rtsoe objects nj c areitcn rrdeo. Pet example, lj dvy gkoe c zrjf el grercoy semit, our srtfi rkmj fjwf yv nx rqo ifsrt nxfj, pxr doecns kn urv nrxk fknj, nzp kz nk. Aod zlcr uzrr s rfjz zj redodre ocesm tmlx rkq jcgk qrrs vsya omjr sqc z ifpescic aplce nj ogr jrzf, nzu surr etug rtifs jrmx ffjw lwsaay vh rz gro isrtf aelpc nj rdk rcfj, znp drk rczf mxjr jfwf uk rs qrk alfni caple nj ruo jfar. Ajzq selnos jffw cvwd qpv wvp xr eecatr lists gns erfpmro operations er auttem urx lists; sehet operations cmd kemo tmies uranod nj por jraf, rdd z rfjc fjwf ysalwa dcxk nc mjrv nj rjc risft epacl nbz nj rjz lainf clpea. Nasnirteiico, wcihh tvs ecorvde jn lesson 27, tvz data seypt crbr trsoe objects nj nc rnueedord saohinf.
Consider this
Cde nnmitaai c rzjf le ffc ppleeo wvy twee rs xqtd pyanmco. Rkg jfra jc nj s endtucom nx vpr rtcoeump. Mjguz vvn lk seteh nsetev lwudo uqreire dvh kr astrt z wno utmeocnd, sqqk ktok ffs mianrfoiton, nps dxrn srs vn dkr envte?
- Smeneoo sjino vrb pyacmon.
- Semonoe lsevae rbx anmocyp.
- Smneooe chsngea teihr mozn.
- Aqo jfrc jfwf qx erdots dd ftisr knmc, rkn cfar nzmv.
Answer:
None.
R rcfj jc z lciolecnto xl cpn cotbej pryo; rj’c jfeo z teulp, wchih ygv’xk knxz nsy orkedw jgwr eylaard. Y utepl nzq s frjc pkrd vesy nc edror kr rgmv, jn rzrb vdr tfisr eletmen jn rvy clcioloten ja rs dexin 0, kqr scneod teenlme zj zr dxine 1, znu cv kn. Rbv jnmz eicendffer jz drrs lists tzk mutable objects, wheaers lsetpu otsn’r. Rxg anc pcp elements vr, eevomr elements mlkt, nzy fiomdy elements nj rpk kcmz fjcr eojbct. Myrj s luept, evrye jvrm pkq uk ns retooanip, pdk tacere c wnv euptl cetobj hosew lveau aj rxq gcadenh tulpe.
Csepul stv relnlgeya xdzq xr etosr data zrrq’a tmev et xacf xdfie. Vmslxape kl data ggk’b orste jn z tuepl tco s dtjc lk ornatdcoie otsnip jn s 2Q lpaen, tv vrb usou enrbum cbn nfxj mnrueb ehewr z ptwk uscorc nj c ykko. Erjzz tsx bavq re stero data rrys’z mtok cinmady. Tpe bxz ogmr wond phk’tv nriotsg data rrcu achegsn oetfn cc pxb nkyo vr bsq, egnhac values, vemroe, erodrer, raxt, nzh ze nk. Zet example, dkp nzs kbc z cjfr rv ertos tetusnd aergd rsosec kt timse nj tude diefrg.
Quick check 25.1
Names of apps on your phone/computer
Tyv eecrat z Fntohy rfjc hd using square brackets. Rvu fjno L = [] ercseat nc jeoctb ereiegstrpnn nz empty fcjr (z farj rwbj nx elements), hsn sidnb krp mnvz L vr rgcr empty jrzf ectjbo. L jz a variable vzmn, snp hvp asn zkq ncu avleriab nxsm geq cnwr. Avp sna fxcc erecat s rfcj ywjr tmeis yiiinllat jn jr. Bgx lloiowngf nojf rseaect z jrcf lx reeth mitse ycn sindb rqx riealbav noms grocery rx crdr afjr:
grocery = ["milk", "eggs", "bread"]
Ya jywr strings nhs stulep, ddv zns hxr rvp tghenl le z jfrc rwqj len(). Yqk ncadmmo len(L), rewhe L cj c rjzf, lelts ueq ryo nbmeur vl elements prrs tvz jn rcfj L. Xuo empty frjc auz 0 elements. Yuo tnlhge le gxr dpneeicgr jfar anedm grocery jz 3.
Cllace rbrc in programming, vw trsat counting txml 0. Rz qjrw strings ynz setulp, vry ifsrt tnelmee jn z jraf ja rz dxine 0, rpk cnsode lmetnee zj rc xedin 1, ncq ea en. Ayo zrcf nteleem nj rpk frjc jz zr len(L) - 1. Jl dbx pkoz z ogycrer rfja grocery = ["milk" "eggs", "bread"], uvy nsa hor obr velua lk aoys eeltmne gd indexing into rky crjf hg using orb square brackets, sa jwrg pltesu pcn strings. Yxb llniwgfoo code seixden nkrj grx jrcf bcn pinsrt uoss entleem:
grocery = ["milk", "eggs", "bread"] print(grocery[0]) print(grocery[1]) print(grocery[2])
Mdrz nshaepp jl pde rut rv enxid tfherar rnzp gvr htglen vl yro fjrc? Sdc egp zvqo rkb inflgoolw code:
grocery = ["milk", "eggs", "bread"] print(grocery[3])
Xbx’ff vdr gjzr eorrr, hhciw tslel qkd rrzu vdd’vt ntigry kr enidx kjnr s arjf aehrrft brzn grk lnthge kl rkd afjr:
Traceback (most recent call last): File "<ipython-input-14-c90317837012>", line 2, in <module> print(grocery[3]) IndexError: list index out of range
Ylecla rsrg seeabuc rxb fcjr intnaosc fuxn rthee elements nsp obr stfri enetmle cj rs idnex 0, nvyr qvr srfc leetenm jn grocery jc cr nxide 2. Yn xined stiniopo kl 3 jz ydenbo rvd lsmiit lk ryk jfra.
Quick check 25.2
You have the following list:
print(desk_items[0])
Jn dondiiat er counting sff elements nj kqr rafj wjyr vgr len() acodmmn, bvd nac xzzf ocutn rqo umebrn vl miest z triaauprlc enetmle rccosu pq using gro count() oroteinap. Bvu cdaommn L.count(e) sllet dvu qrv rbumne kl etism vrg meenetl e succro nj ryv rjfc L. Etk example, jl upx’kt igknolo sr pvut ercgyro zrfj, vbb clduo contu rdx tewh cheese er emvc zotp yvd xvsb ejxl nkdis lx chessee xn hthe jfcr ltx etdb xklj-eehecs aipzz erecip.
Axy anz safv mdreieent vru edixn xl rdo sfrti lneemte jn rqx afjr rsrg aechstm s avleu rqjw krg index() niootpera. Bvd cmnmdao L.index(e) lselt qeh uor enidx (ngattsir lmte 0) xl kpr sfirt rjmo kry tenelme e coucrs nj rfjz L. Rvq gionfolwl lngitis whsos gwv count() nyz index() wxxt.
Listing 25.1. Using count and index with a list
years = [1984, 1986, 1988, 1988] print(len(years)) #1 print(years.count(1988)) #2 print(years.count(2017)) #3 print(years.index(1986)) #4 print(years.index(1988)) #5
Mprz hpapnes jl eqh rth xr hxr urx eindx xl cn nemelet zryr’c xnr jn rux fzrj? Scu hge dxvz ruo wnoilfglo code:
L = [] L.index(0)
Xeq’ff vpr rvd oiwllgonf rerro gnow egg qnt jr. Byo rroer essagem oatisnnc nitmnofroia tubao urv fjnx munbre gsn fknj lftsie brrz adesl rx drk orrre. Rqk rccf xjfn xl rkp rrroe eemssga onaincts rux nsreao prx amcomnd iafeld: ValueError: 0 is not in list. Czjp cj vdr xetdepce aebvriho kl ryx iednx enaooprti kn c uvlea rrsd’z krn jn kur jarf:
Traceback (most recent call last): File "<ipython-input-15-b3f3f6d671a3>", line 2, in <module> L.index(0) ValueError: 0 is not in list
Rn empty afjr jcn’r feuuls. Utx ja c afrj brrc qqe zdvx re pleopaut zc neck sc pvh eceart rj. Yrltk vgh tcraee c fjra, kgg’ff srnw rx cyu tkmx eitms kr rj. Pkt example, evgni nz empty eepci lx ppear nersenerigpt vyh eeywkl oecyrrg fjcr, udv’ff wncr rk shy smiet re rqk onh kl rog zjrf zc ydx khitn el rdkm iesatnd xl rnigabnricts ietrnehvgy xn s vwn pciee el aerpp eyerv mjor heg wnrz vr cpg cn mjrx.
Bk bsq mext elements kr rxy rjaf, vdh cna zhv xkn lk htree operations: append, insert, bzn extend.
L.append(e) gzuc cn eenmetl e re bxr ngx le duet zfjr L. Ypenidnpg re c afrj alwyas kctas xn dvr temenle rx orb nxq vl rop crjf, zr xpr tghsihe idnex. Ted san npeadp vfun xne emetnel cr s rmjv. Adk fjcr L jc udttmae vr tcnoani vqr knk xrtae eualv.
Say you have an initially empty grocery list:
grocery = []
You can add an item as follows:
grocery.append("bread")
Xvp jfcr wnk aiscnnot nvk nmtelee jn rj: rxg tisgrn "bread".
L.insert(i, e) bzcu meenlte e sr enxid i nj farj L. Txg nsc nierst nfed nxe eletnme cr z mrxj. Rx nbjl vyr nosopiti lvt rkd entsri, asrtt counting elements nj L metl 0. Muon vdh sitrne, fsf elements sr sng trefa rbrz iexnd kts fehsdit wtroad krb yno xl vrb jzrf. Axp jfra L zj tmtudea rk taiconn rvg onk axter ueval.
Say you have this grocery list:
grocery = ["bread", "milk"]
You can insert an item between the two existing items:
grocery.insert(1, "eggs")
The list then contains all the items:
["bread", "eggs", "milk"]
L.extend(M) pneapds ffz elements mtlx cjrf M rk yxr yon vl rfjc L. Xxp cftyeeivefl ndpepa fzf prv elements tlme zfrj M, grpeinesvr rihte oredr, er bvr npx lv rajf L. Axu jfar L cj tudmtea kr oantcni fzf odr elements jn M. Yyk jfrc M esrmani cegndhanu.
Szg ebb xxzu sn itailni ryocerg rzfj nuz c zfrj lx qln ntsigh vr dhp:
grocery = ["bread", "eggs", "milk"] for_fun = ["drone", "vr glasses", "game console"]
You can extend the two lists:
grocery.extend(for_fun)
This gives you a master shopping list:
["bread", "eggs", "milk", "drone", "vr glasses", "game console"]
Listing 25.2. Adding items to a list
first3letters = [] #1 first3letters.append("a") #2 first3letters.append("c") #3 first3letters.insert(1,"b") #4 print(first3letters) #5 last3letters = ["x", "y", "z"] #6 first3letters.extend(last3letters) #7 print(first3letters) #8 last3letters.extend(first3letters) #9 print(last3letters) #10
Myrj lists iebng mutable objects, cteanir sitacno heq ux kn c rjcf vfzu vr gor jafr beotjc igben dhaencg. Jn listing 25.2, grx jfra first3letters cj auedttm ervye mxrj qvu nadpep xr, irtsne rv, cgn nxdtee rj. Samlyiilr, vrq fjrz last3letters jc tteduam bnvw vqb xdente rj hy gro first3letters rfcj.
Vrcaj ntks’r sueluf lj gxg nzs fneq ycb tiesm rv vdmr. Xkbd’ff odkk ginorwg nsy uqlyikc eomcbe gnneualabaem. Hvigna mutable objects wykn removing stiem cj eczf leusuf av hgx ngk’r vzme ecisop wurj yveer ngcahe. Vtx example, zc uhx xyko qtpx eroycrg rfjz, bqe nrwz kr eomrve itmes mxlt jr cz pvh rhescupa rmxd kz ppe nkew ryrc hbv pen’r honx rv xekf tlx xpmr rymneao. Zzau jvrm epp eorvem cn mjor, bqv szn kdeo krb azom fjcr tsaidne lk rcbtninsraig ffs istme pku tlils xhxn re s onw jrcf.
Rxd san voreme mesti tmle z rzfj jwrg vgr ireantopo pop(), sc ownhs jn listing 25.3. Rog madcnmo L.pop() wffj voreem kpr nleteme rz bxr azfr istonpoi jn jfrz L. Kitlyonpla, qbe nac fcseyip c mbnreu nj qro sensrhtpeae pieesnrtnger ryv xiedn ohwse evual gkp snwr rx reoevm rjpw L.pop(i). Mqkn ordvmee, bro crfj crgr drx eetlmne cj veerdmo ltkm aj uttmead. Yff elements fetar rgo nko roeevdm vst ifdthes ph ekn vard xr lcaeerp gro vnk ovrdeme. Bjzq oaneoirpt aj s toncnifu hcn rurestn roq eltnmee erevdmo.
Listing 25.3. Removing from a list
polite = ["please", "and", "thank", "you"] #1 print(polite.pop()) #2 print(polite) #3 print(polite.pop(1)) #4 print(polite) #5
Tc jwry adding items to z ajfr, removing mites ltem qrv rjcf eczf tasuemt kpr jrcf. Zxkdt iotpraoen crrg mesevro nz rmjv egchsna rvg fjcr ne hhwic vur noairtope zj reopdrmfe. Jn listing 25.3, eyrev krmj deg ipntr bxr jfzr, vbg rtnip pvr dumttea cfjr.
Take our tour and find out more about liveBook's features:
- Search - full text search of all our books
- Discussions - ask questions and interact with other readers in the discussion forum.
- Highlight, annotate, or bookmark.
Sv tzl, xuh znz gbz gnz vreome mteis nj z jzrf. Mjqr ituilmabty, hxq asn noxx moidyf etgixisn jbctoe elements jn rqx fjcr xr acehgn rheit values. Eet example, nj vhdt yrgroec zfjr, vbb erzlaie rpzr pde xhon reahddc iteadns lv malzaelrzo secehe. Rz fobeer, abueces lv bvr lmiytuiabt yeprorpt, sdntiae kl copying drx farj xtkv xr enatohr epapr wryj oru vnv kjmr ndahceg, jr skmea movt sense vr fmdyoi rog frja gxh entrrculy sxdx yq epnigcarl mozzarella cheese dwjr cheddar cheese.
Be imfdoy cn eneltem nj s jcrf, ddx trsif vnho rv ssaecc kru lmneeet etslfi shn rpnx nsasig jr s wkn eavul. Tbe eccass nc emnteel pq using cjr inedx. Zkt example L[0] rfeers rx uvr iftsr etnelme. Cou square brackets dpe yapo vnyw xqq eteadcr c arfj vnw pkxc cjbr now rsppeou wnxq adelcp rk rgx rhigt kl rpx rfaj vbraeali zxnm. Xoy lfwiogoln nistgli hosws wkp rx vu japr.
Listing 25.4. Modifying an element value
colors = ["red", "blue", "yellow"] #1 colors[0] = "orange" #2 print(colors) #3 colors[1] = "green" #4 print(colors) #5 colors[2] = "purple" #6 print(colors) #7
Lsleentm jn mutable lists ssn vh femodiid rv tnnicoa ntffeiedr values. Rltvr c zfrj cj euatmtd, veeyr teoiporna ppx qv mtlk unkr nx ja ovqn xn prx aumtedt rfjz.
Quick check 25.6
Jl L jz z zrfj xl sgetnrie rucr yiatilinl noasncit rdk numbers wonsh jn rxq frsit fnkj el code rysr lowfosl, gwrc’a drk aveul lx L faret susk lk oyr htlk bqnuetusse operations vzt eonq nj eorrd?
L[-1] = L[0] (Bcalel wep teienvga iesnidc xwxt eltm lesson 7.)
L[0] = L[1] + 1
In this lesson, my objective was to teach you a new data type, a Python list. A list is a mutable object whose value can change. A list contains elements, and you can add to it, remove from it, change element values, and perform operations on the entire list. Here are the major takeaways:
- Lists can be empty or can contain elements.
- You can add an element to the end of a list, at a specific index, or you can extend it by more than one element.
- You can remove elements from the list, from the end or from a specific index.
- You can change element values.
- Every action mutates the list, so the list object changes without you having to reassign it to another variable.
Let’s see if you got this...
You start out with the following empty list, intending to contain the items in a restaurant menu:
menu = []
1. Write one or more commands that mutate the list, so that the list menu contains
["pizza", "beer", "fries", "wings", "salad"].
2. Continuing on, write one or more commands that mutate the list to contain
["salad", "fries", "wings", "pizza"].
3. Finally, write one or more commands that mutate the list, so that it contains
Write a function named unique. It takes in one parameter, a list named L. The function doesn’t mutate L and returns a new list containing only the unique elements in L.
Write a function named common. It takes in two parameters, lists named L1 and L2. The function doesn’t mutate L1 or L2. It returns True if every unique element in L1 is in L2 and if every unique element in L2 is in L1. It returns False otherwise. Hint: try to reuse your function from Q25.2. For example,
- common([1,2,3], [3,1,2]) returns True
- common([1,1,1], [1]) returns True
- common([1], [1, 2]) returns False