You are on page 1of 28
a Manipulation “Iq vie Charter 7.1 Introduction 7.2. Creating and Accessing Lists 73. Ust Operations 74 Working with Lists 75. List Functions and Methods INTRODUCTION The Python lists are containers that are used to st variables Python lists are mutable fe, will not create a fresh list when you Sequence like strings and tuples but it differs fr strings and tuples are immutable. This chapter is dedicated to basic list muanipul Creating and accessing lists, various list opera builtin functions, you can change the elements of a list make changes to an element of a ‘om them in the way that tore a list of values of any type. Unlike other in place ; Python st. List is a type of lists are mutable but ation in Python. We shall be talking about tions and list manipulations through some SING LISTS 7.2 CREATING AND ACCE: sequence of values belonging. Jn store 3 sa jat ga standard datatype of PytHOn MMT A eg, following are some liste in fy) ; rough $4 . Y type The Ls re dep MOEN geben, emoty st Qo List of integers os and floating point) 0,231 glist of numbers (Satese glist of characters ist of mixed value tyPes we) 1, 'B, 3.5, "2erc] Lone’, ‘Two’, ‘Three’) ist of strings « to create lists, one thing, Before we proceed and discuss how (0 fen Tesla) = ci ists are mutable that must Be clea i that Lat re mu ord ss ate mat tay, you can change elements of @ er yout Python Le, a not change even alter y s YOU Cn they evo mutable types of stementsofa tnt, the memory address of a list vil change its values. List is one of Ul c types o Pylon Lists ond Dictionaries are mutable types all other data types of Python are immutable. = 7.2.1 Creating Lists | ; To create alist, put a number of expressions in square brackets, That is, uss square braces, indicate the stat and end of the list, and separate the items by commas. For example: (2, 4, 6] rer ae (1, 2.8, 3, 4.0] —3 ( ree , data pes, Thus to create a list you can write in the form given below 5 an uo L=[value, ...) ‘This construct is known as a list display construct Consider some more examples : © The empty Ji The empty list is [ ]. His the list equivalent of O or" and a like them it also has truth value as false, You ean also - create an empty list as : LUsts are formed by plat ‘comma-separatedist of oF L=list() sssions in square brackets twill generate an empty list and name that list as L. — © Long lists If a list contains many elements, th " several lines, like below : len to enter such long lists, you can split it ao SqrS=[9, 1, 4, 9, 16, 25, 36, 49, 64, 81, 200, » 16, 25, 36, 49, 64, 91, 44, 196, 225, 256, 289, 324, 361, 400, 441, 4 108, 121, 144, 169, Notice 84, 529, 576, 625} te lotice the opening square bracket and just io Sean a are b and closing square brackets appear just ist MANIRULATION o Nested Wists 229 iw have an clement in it, whet elt Wa ls Such alist scalded nea ment ln It which isett tea tnt, ee + Such a list is called nested list, eg, LI Is a nested list with four o Leng of L184 38 i counts (Ses 28 A. 5, 6 a (5, 6] a5 one eas ind 7, LAL2] element ts a list [5, 6) eating Uisls from Existing Sequences vu can also use the built-in list type given below : Object to create lists from sequences as per the syntax [= Hst( can be creates the individual el you pass in another list, the 1d of sequence morn object including strings, tuples, and lists. Python list from the individual clr z lst funtion makesacopys mmf Ped neuen. Consider following, examples >99 d= list(‘hel lot) vod * th, 'e, Ui 1 i crear anther soguence ating “het (i penraed ind elements fom the India ter ofthe wing pote (W,'e,'r,'t,'y) poo Ide Mst(t) . SS rit mi trp nial ees for he Re) feds conn eos pe rota fram another sequence You can use this method of creating lists of single characters or single digits via keyboard input. Consider the code below : 11 st(input( ‘Enter List elenents:")) enter List elements: 234567 ood — (2,3, 4, °5,,'6, 71 Notice, this way the data type of all characters entered is string even though we entered digits. Tocnter a list of integers through keyboard, you can use the method given below. Most commonly used method to input lists is evalfinput()) as shown below : I: col) wis t ety pe by looking at st « eval (input( "Enter list to be added:" )) 4————~ ‘he gin eprestion (Rud on eat pape) print (“List you entered :*, 11st) See it erat te lett of it ing foc of the character input When you execute it, it will work somewhat like : Enter List to be added: (67, 78, 46 23] Ust you entered : [67, 78,46, 23) Pease note, sometimes (not always) evall) does not work in Python Shell At that time, you can » sometim c Tun it through a script or program too. 7.2.2 Accessing Lists suo an emresson sens iy \ | ate and return the re to evalu “The eval, )fancia of Py can Be w#e9 For example eval('5+8") will give you result 36 33 Similarly, following code fragment y+ eval("3*10") print(y) will print value as 30 Since eval() can ia pres wu can use it with inpul( ) too M rerpet an expression given as string, You ca" UES with inp ir am i an ex vari = eval (input("Enter Value:*)) print(vart, type(vart)) Executing this code will result as: enter value: 15 +3 48 1543" as 16 but also stored the result as int value. Thus . the eval() has not only interpreted the string vari = eval (input ("Enter Value:")) vara = eval (input ("Enter Value: “)) print (vara, type(vard)) print(vart, type(vard)) Enter value: 89.9 Enter Value: 75 89,9 75 You can use eval( )to enter alist or tuple also. Use [ | to enter lists” and () to enter tuple values vari = eval(input (“Enter Value: ")) var = eval (input("enter Value: *))| print(vard, type(vari)) print (vari, type(var1)) Enter Value: (2, 4, 6, 8) Enter value: [1, 2, 3] @, 4, 6, 8) O, 2, 3] ‘However, use of eval( ) may lead to unforeseen Problems, and thus, use of eval( ) is always ascouend ] Lats TUleble (editable) sequences having a progression of elements, There must bea!" ces is individual elements and Fo ee But before we start acessing indivi a ity Of Lists with tri a to} Pantie ‘ strings that esr} re cnigtidual elements are accessed in lists ~ the way you one sum aiets Following hoot 7: UST MANIPULATION, Similarity with Strings 231 & agen stings. tn the some manner fe. REC figure 31 of chapter 3 Wee tae ence 9.4.23. and backward indexing og oh TEM ae als indeed te. forwert none Maem 05-12. Bo Sec eng ee orwanindonngas shen ey elas at slesdol ue Saracer as nag Esch tne nrc dors fare (6) Mow ists ae internally ciganized a Thus, you can access thelist elements just like ess astring’sel ist wi you access astring’s elements cg, List{i will give you the element at ith index of heist; Lala. will give you samen blows nese b~1 and so on. . Put in another words, Lists are similar to strings in following ways : © Length Function len(L) returns the number of items (count) in the list L © Indexing and LL] returns the item at index / (the first tem has index 0), and L[i:j ] returns a new list, containing the objects at indexes between i and j (excluding index j). © Membership operators Both ‘in’ and ‘not in’ operators work on Liss just like they work for other sequences. Thatis, in tells if an clement is present in the list or not, and not in does the opposite. © Concatenation and replication operators +and * The + operator adds anc list tothe end of another. The * operator repeats alist, We shall be talking about these two operations in a later section 7.3 ~ List Operations. wn COMPUTER SCIENCE WITH PITHON - fo p coessed — ind nis list are a ‘Accessing Individual Eleme’ ements of 8 : e ot “As mentone the individal em apes Wille 222536 elemen,y FO h their indexes. Consider you pass In 3 negative Le throug} w) Python adds the length oye? | soo vowels» (3 oe Igtto the Index to get element $0 39 vowels [2] forward Inder. Tha is fet 3 Gelemert Ht L, Us) way i Internally computed as: 2 vote TU a soem, gre 2 vasa 2 aw 1 >>> vowels[-5] te ne v = 1 or length, ~ length +1, 100F ; ve tne legal indices (0 t0 lenght i one Uke tring you give index cur ee Python wil raise Index Error (sce below) ites uptll -1) while accessing individ val elem wy >>> vowels =['a, "et, ‘0, U] and aes {5 sno ea inde for vowels tis. thus eariot So voweli[e) ie eat te acces atid element ) Traceback (rost recent cal Last): | File “", Line 4, in crodule> | vowels[5] | Cor | Indextrror: List index out of range it mt Difference from Strings : Although lists are similar to strings in many ways, yel there is an important difference in 1 mutability of the two, Strings are not mutable, while lists are. You cannot change individual elements ofa string in place, but List allow you to do so. Thal is, following statement i fully =m valid for Lists (though not for strings) : Lf] =celenent> | For example, consider the same vowels list er reated « ; Now if you want tochange same of these vowels. above, that stores all vowels in lower case. . You May write something as shown below: Sa > voels[o] vowels Notice, it change the eerent in at (A, 'e, tv] feces 0 A) no mew [ont | >>> vowels[-4] a" MUTABLE, i Hists are Usts are similar to strings At: >>> vowels many ways like indexing, sliché At - i CAE, 0, uy and accessing individuatelemens | |g t , but they are different inte | | gg I Traversing a List Sense that uists are metobe | | Recall thas while strings are not. ¢ at traversal of a = cy | traversing alist also means Went Mea access Ma t Why sometimes we calf nett S2m€ and same je eqn PFOCessing cach element o Y } calla traversal as | is the tool for it, ip looping overa sequence,” the Python loops. That 5 P over the itemsin alist, as per following syntax: for in cLists; = . process each tes here For ample, fllowing loop shows each item of L=(P,Y,'t, foraint: print (a) list L in separate lines : The above loop will produce result as : How it works The loop variable a in above f loop-variable 3 will be iteration, » will get ele loop will be as assigned “Pin first ite ment ‘y" and ‘y’ will be Ifyou only need to use th and len() as per followin signed the List elements, one at a time. So, “ation and hence ‘P’ will be printed ; in second Printed; and so on. we indexes of elements to access 1g syntax them, you can use functions range( ) for index in range(en(t)): process List[index) here consider program 7.1 that traverses through a lis using above format and prints each item of a list L in separate lines along with its index Pp FA Program 1 print elements of a hist [4 both inde tive und negative. an LaLa, We, ty) length = len(L) fora inrange(length) : print("at indexes*, "©. ¥°J in seporate lines along with element's “and”, (a - length), “elenen! Ua} Sample run of above program is : | At indexes 0 and -6 element : q At indexes 1 and -5 elenent : w At indexes 2 and -4 elenent : € | At indexes 3 and -3 element : | At indexes 4 and -2 elenent : t | At indexes 5 and -1 element : y Comparing Lists You can compare two lists using standard comparison operators of Python, i.e.,<, >, Python intemally compares individual elements of lists (and tuples) in lexicographical order. This means that to compare equal, each corresponding clement must compare equal and the {wo sequences must be of the same type ie, having comparable types of values. fs etc. Consider following examples: devia, L2= EL, 2, 3p (2s 2 3] pode, [2,31] >>> LD am L2 True poo Lies La os canding elements of two Hists must by est For comparison operators >< >=» <1 the eoeespe comparable types , otherwise Python will gi ove two lists : For fist comparison, Psion didnot give any eroras fot at hae vals of Sere fp Consider the following considering the ab poo Lela xaeare faise For sco compari, 2 he aes of >>> Ld ”, line 1, in »>d= [2.0, 3.9] ven [2, 3, 4] D> aeeb True . >» False Fee m0 tts be ‘alues(ecal int anf There is also a emp) functio, covering it here. 73. UST OPERATIONS The most common operations and slicing lists. In this section, we are going to talk about the same. 7.3.1 Joining Lists Joining two lists is very easy operator +, when used with tw >>> Istl=[1, 3, 5] >>> Ist2=[6, 7, 8] >>> [stl + Ist2 (1, 3, 5, 6, 7, a} As you can see that the sesu clements of second list Ist2. You can also join two or more lists to form a new lst, eg, o> [sth = (40, 12, 14] 999 Ist2 = (20, 22, 24] >>> 1st3 = [30, 32, 34] >>> Ist = 1st1 + 1st2 + 1st3 >>> Ist (ie, 12, 14, 20, 22, 24, 30, 32, 34] The+ operator when used with lists requires that both the operands must be of list types. You Sannot add a number or any other value to a list. For example, into error : list + nunber list + complex-nunber Uist +string 4 The operator eoncatensies te lists 235 “a on Intersil compares individual elements of tivo lists, % you have read earlier. Consider following codes >marb False Doda False >>dena True atic for comparison purge, Dh (guned the typeof elements ra corporal vues eal ace True rar pett nt kav seme wanker of eens oad marching lat wih marching vuluce ae conser fea), that can be used for sequences’ comparisons but we are not that you perform with lists include joining lists, replicating lists just like you perform addition, literally +). The coneatenation 0 lists, joins two lists. Consider the example given belo, ‘and erates a ew fst Mant list has firstly elements of first list fst and followed by The + operators we to concatenate 4 tee intr Ett pel oc combined lis It following expression will result win conmutér SCIENCE WITH THON < ing exam seated whe anti Consider the following exampl enrgteatt pop Ast = (28, 22, 24] sey pop Asta +2 racobock (most recent ea10 2088)5 Fale “epyshell#az»", inet, 5 7 ) toss nae int") t0 ‘aera ‘can only concatenate 11st (not yoo Ista + "abe" 1 Last): Traceback (nost recent call 19st): Tile "epysheli#aa>", Line 3, in ceodul era on {not “str") to list Typetrror: can only concatenate 1ist 7.3.2 Repealing or Replicating Like strings, you can use (considering the same list Ist? = [1, 3, 5] ) — The + eneazr rept alist specifies = tex new i popistt3 | <————— umber of times and rea (2, 3,5, 1,3, 5, 1, 3,5] Like strings, you can only use an integer with a * operator when trying to replicate a list. 7.3.3 Slicing the Lists List slices, like string slices are the sub part of a list extracted. out. You can use indexes of list elements to create list slices as per following format : seq=L[start:stop] Lists . . * operator to replicate 2 list specified number of times, eg, When used with lists, the + ‘operator requires both the operands as list-types; and the * operator requires a list and an integer. The above iecment will create a Fist slice namely seq having elements of list Lon indexesstart starl+l, start42,...4 stop-1, Recall that index on last limit is not included in the list slice. The list ‘terisalistinitself, thatis, you can perform all operations on itjust Consider the following example ; est =L10, 12,24, 20, 22, 26, 30,32, 34) 92 Seq= 1st [ 3: -3] >>> seq (28, 22, 24] 99> seq 1) = 28 >>> set : » i ae Tarn 0 modify an emery ene roy at does bo cg e ae he list slice seyhs ats iniueyp like you perform on lists. re “Ustrstopy creates se Out of list Lwith elements falling between indexes start andst0P, ‘ot including stop. Seems 17ST MANIPULATION ; ot 237 cn ve boundaries, Forint wera instead, and the ren ay vaty eames items pve the stop given na lartbegs ind), Python simply retums the gleme It sin ata ere 8 that fall bet if Forexomple, consider the following : the list, yop Ist «120, 22, 14, 2, 22, 24, 30, 32, a4) pyo Ast [3238] 4 Giving per ins (20, 22, 24, 30, 32, 34) {ut bt hon ta de fo app Ast [-15 :7] : Inrange Formate te line (20, 22, 14, 20, 22, 24, 30) ~~ ising one tin uc ker, bet +—_ PEPE cerns from lst falling in range -15 onwards <7 yr 412, 3, 4,5, 6, 7, 8] ee degenerate 0.8 pop LL (2: 5] i irbex range is 0.8 and -7 =) 56) port [6:18] 3 One tints out of bounds 18] $s enor tr etums bls as por pve a poo Lt [18 : 26) <—__ - oa tiits ne out of ens + —~ Poston gives uo error ae rerum an enpey sequen as ta elenirt of E4 has index fling in rae of 10 0020 Lists also support slice steps. That is, if you want to e: tract, not consecutive but every other element of the list, there is a way out lee ~the slice steps. The slice steps are used as per following form: Ulstort: stop: step} creates a st te a slice out of list L with elements seq=L[startzstop:step] falling between indexes start Consider some examples to understand this. and stop, not including stop, Skipping step-1 elements in dolst between [20, 12, 14, 20, 22, 24, 30, 32, 34) = at astro £1022] Mite eer erent, ip element i in beesen Check eubing sce 2! - ‘ [, 14, 22, 30, 34] +-. ——_ ‘avy Jnl element, fe, akip 2 elements pods 11023] — (4, 24, 34] —— st stop § daly step is given as 5 That is, from eee Consider some more examples : Seq=1[::2] # get every other item, starting with the first , Seq= 15: get every other item, startingwith the sixth elenent, {.e., index ' je 30, 12, 12, 32, 24 25 16, ren SCENE WOHIPTHON id pie in felemohso py | ty aenes (015, POGrEM shou gi, calig every four efemen of i ‘ sun+ea, | print (a, end" ") Sample ran of above program is Hpsp print () . eh print ("Sun of elenents of slice 1:", sun) slice 1 | print ("slice 2") 6810 1214 ; | sun=@ sun of elements of slice 1: 50 | slice 2 fora in sie? : I Oe mea 1593317 i print (a, end" *) average of elements of slice 2:9 print () ' avg = sun /len(sle2) print ("Average of elenents of slice 2:", avg) Using Slices for List Modification You can use slices to overwrite one or more li s wil elements. or more list elements with one or as 0 more other . Following examples will make it clear to you : >>> L= [one", "two", "THREE"] >>> [2:2] = [ 8, 1] <—__ sien new values to ist sice ara (0,3, "mcery Ges Soir nt eich >>> Le["one", "two", "THREE*] >>> L[O:2] = "a" rk TAREE] A Ne what es apo In il the above examples, we have ass being assigned quence, i, a tc. 'B assigned must be a sequence, ive, list or stri ing or tuple et igned ne js 'w values in the form of a sequence. The values 74 wl caaper 7 UST MANIPULATION 239. <_ Forexample, following, assignment is also valid, po Ld = (1,2, 3] 299 LY TB) 0 6 me : por kd (1, 2,3, '6", "0", "ay £¥ Bat if you try fo assign a non-sequence value toa list sige such asa number, Python will give an error, fe 99 U1 [2 2) + 345 103 enunty, mv a eyuree Filewc. >) Line 2 Sn éncttules Ua [22] «345, TypeError: can only assign an iterable But here, you should also know length of the list it will simply omething. If you give alist slice with range much outside the ddd the values at the end es. vor bbe [1, 2, 3) >9 LA [10 t 20] » “abcd” *———_ sas ee re hough it slice fit ue ounide apd the kent. Now Pho wil append the Laer, > tothe endof tat 11 12,3, a", ~ wet, td") « 74 WORKING WITH LISTS Now that you have Mt 10 access the individual elements of a list, let us talk about how you can perform various operations on lists ike : appending, upslating, deleting ete, Appending Eleme s 10 a List You can also add items to an existing sequence, The end of the list. It can be done as per followin Coappenia( ite) Consider some examples poy Astd = [20, 12, 14] append() method adds a singleitem tothe format >>> Ist .append(16) o> Ista Median en eli eed tthe el ef exit lan [20, 12, 14, 16) «- feasting Updating Elements to o List To update or change an element of the list in place, you just have to assign new value tothe element's index in list as per syntax : ‘Utnde] © > Ast = (18, 12, 14, 16) a -. 1sta(2] «26 << $e stg net ee > Asta Display thelist 10 se the pated lst [20, 12, 24, 16) — ‘ COMPUTER SCIENCE WITH t ean be used to remove an ‘The del statemen” Tr used as per syntax iene 15 from 0 Lis Deleting Elements a from lists. 1 .n algo remove items Ir - sli You can ae ave al items identified PY t remove elemen' del List [ : Ist =[1, 25 3, 4, 5s 6» 70 8, 9 >>> Ast #[1, 2 weer in mare Dele elo , >a ttf] Ge oe aa gvdtrl Compare with i bore pees 18, 19, 20) [3,25 3, 4, 5, 6, Zo Bs 9p 38» 32s 33, 14 15, 16, 171 spveen indexes 10 10 15 in list >> del Ist( 28:15] +————— al al een se le so Ast ’ 20) [1, 2, 3.4, 5, 6, 7, 8, 9, 18, 37, 18, 19, If you use del only ¢.g., del Ist, it will delete all the elements and the list object too, ‘After this, no object by the name Ist would be existing. You can also use popl } method to remove single element, not list slices. The popt ) mettat removes an individual item and retums it. The del statement and the pop method do pretty much the same thing, except that pop method also returns the removed item along with deleting it from list. The popt ) method is used as per following format : List.pop( ) # index optional; if skipped, last element is deleted Consider examples below Soo dst =, 203,455, 6,7+8,9, 20, 11,22, 13, 16,25, [oho 16, 17, 18, 19, 20) ] While del statement can remove >>> Ist.pop() a single element or a lst-sice 28 from a list, the pop( ) an >39 2st.pop(16) Femave only single element, rot hn Uist slices. Also popt ) retruns the ; deleted element te The pop( ) method is useful only when you want to store the === = element being deleting for later use, eg, iteml = L.pop() # last item item = L.pop(o) # first item iten3 =L. pop(5) # sixth item Now you can use item|, ite ; item? i Gey and item3 in your program as per your requirement. yee Usts IN PYTHON - | 6 Progress In Python 7 ‘This PHP session works o: the opises : the objective of practicing List Manipulati ulation operators. aay bite) St ete Sometimes you need to make a copy of alist and you generally tend to do it using assignment, e.g., ae(2,2,3) Toying to mae copy of tat a bea inti put twill ot make B as a duplicate list ofa ; rather Just Hike Python ae dos, it will make label b to point to where label ais pointing to shown in adjacent figure, = ™ Inwill work fine as long as we do not modify lists, Now, if you make changes in any ofthe lists, it will be reflected in other because w and b are like al liases for the same list. See below : pr a=f1, 2,3] >>> bea poo af] =5 >a a is 3) ag See stb isso reflecting the >>> changed value of list a (4, 5,3) See, along with list a, list b also got modified. What If you want that the copy list b should remain unchanged while we make changes in list a ? That is, you want both lists to be independent of cach other as shown in adjacent figure. For this, you should create copy of list as follows : eb-([T TT) b= list(a) — Now a and b are separate lists. See below : >>> a=[1, 2,3] >>> b= list(a) >>> af] =5 >a (1, 5, 3] >o>b Now, list bis not reflecting the changed 12.253] 4 ale, List Bis adependent of list @ » ‘Thus, true independent copy of a list is made via list( ) method; assigning a list to another identifier just Creates an alias for same list. 75 UST FUNCTIONS AND METHODS Python also offers many built-in functions and methods for list. manipulation. You have already Worked with one such method len( ) in earlier chapters. In this chapter, you will learn about Many other built-in powerful list methods of Python used for list manipulation, Every list object that you create in Python is actually an instance of List class (you need not do anything specific for this; Python does it for you - you know built-in ), The list manipulation methods that are being discussed below can be applied to list as per following syntax : . method name> () NCE WITH F) COMPUTER SCIENC! THON , Se bra . > as List only (00 angle Brackets py erring! is Obl rit (e oither a it itera og gt » List with replace a raiftoningesaees 2 Haan ee ee re some useful built-in Tist mé | eran av ook | methods. fom the Fist. Ibis used 25 Per folloygg 1. The index method matched item “This function returns the index of first tus t format! 7 wpe tnd (ED . 7 For example, for alist L1 = [13,18 11, 16, 18, 14). cs a prursnees 2) re ee | : aises on value Error (see below) tem is not inthe list raises exception value Error (see below) | However, if the given item is not i List -index(33) Traceback (ost recent call lest) } 3”, Mine, in File “espython-input-60-038FcSbF2e5¢ / List.index(33) | Valuefrror: 33 is not Sn List | 2. The oppend method As you have read earlier Hist. 1t works as per following syntax : Co a7 that the append) method adds an item to the end of the Th List-append(>» colours, =([ ‘red, ‘green, ‘blue'] >99 colours append('yellow) Diteren * teil >>> colours, a ‘Sv the items gor add at the enlofthelie W , (red, ‘rect, ‘blue’, 'yellau’} Ms The appemi( ) does not retum the new list 1 | consider the following example : just modifies the original. ‘To understand bis i vo lst (1, 2, 3] ——__ 1 >>> Ist2= Ist. append(2) Toying 10 assign the rent of | bea < © ooo st mend) 10 anoter leg 1 wail doo Ist ee Sr 2 is empeyas apendy 4d mot return ay va tn ttt, oy Pri, bas the oe PENAL was Diference between append{ ) and extend{ ) popet 7 UST MANIPLIATION chon! 43, The extend method ‘Theextem!?) method is, also Used for adding multiple elements (given in the formof a list) toa list But itis different from apyper(). First, let us understand the working of extendf ) function then welll talk about the difference between these fie functions, The extend ) function works 38 pe Listextend(9t2=[7, 8] ‘ 2 aprent ) ear tke single acct — de> tl.append(18) AU > whether single item o sale sequence 1,3, 5, 10) eT Neti who wt give mip >>> tl.append(12, 24) largurients (0 oprendi). what harpens? Traceback (most recent cal} 1ast): File “", line 1, in ail ther roe tl.append(12, 14) — TypeError: append() takes exactly one argument (2 given) COMPUTER SCIENCE WITH Pravgy ttn the ryt ener ee Creras 1 ay it lice Ae mats lat ont eeren op tLappend(a2,24)) 4 to ve ist it wall show that mow Ut a. a etic data | [1, 3,5, 18, 2, faite >>> Jen(t2) 5 eno a site eet it j et ar { apo t2,extend(10) C scent call Last)? u Traceback (ost recent e011 1960 Fale “", he | t2.extend(10) ple 5. Yo Typetrror: “int object 1s not iters! ies >> t2.extend((22, 24]) eon pepe a rata con 2? aa obeet element tothe endof alist whe (7,9) a2, 14] oe extend} can adé argunen pp t3 = [20, 40] oo list’s all elements to the endef doo t2uextend(t3) <——— the list. T . pop t2 Jivihat After append! ) the length ofthe sf 17, 8, 22, 34, 20, 40] Sie, ll hate ey atte eit poo ten (t2) Serre Mernal velo ls now only after extend! the engh Hoi kas lenath of inserted it. - i ——— t @ iif = yi 4, The insert method “The iuseri( ) method is also an insertion method for lists, like append and extend methods, However, both append ) and extend{ ) insert the element(s) at the end of the list. Ifyou wantto | insert an clement somewhere in between or any position of your choice, both append Jant | i extend) are of no use. For such a requirement insert) is used. ‘ i ‘The inser) function inserts an item at a n position. It is used as per following syntax: } “List.insert( is the ii i itemise becdice © IM index of the element before which the second argument | Consider the following example | oo tle [a 'e, 'u] >>> tL dnsert(2, ') # inset element y at 4 c ati fn index 2. sect ‘ment insti ot index 2 eee 17: ST MANIPULATION function insert( ), we can say tha For sestisert (0,8) Will insert clement x at the front of the list ie, at index 0 (zero) qusteinsert(1en(a); *) will insert clement x at the end of the list ~ index equal to length of the list ; thus it is equivalent to listappend(x). “Ifindex is greater than Téntlist), the object is simply appended 1f,however, index is less than zero and not equal to any of the valid negative indexes of the list (depends on the size of the list), the object is prepended, i.e, added in the beginning of liste. for alist 1 =( 9", ’e', 'T, “u'l, if we do: “op tL Ansert(-9, *k*) valid negative indexes are -1, -2, -3, -4 poo tl ee eee er # List prepended with element ‘k? 5, the pop methed ‘ You have read about this method earlier. The pop )is used to remove the item’ from the list. Itis used as per following syntax : List.pop() # cindex is optional argument ~ Takes one optional argument aud returns @ value ~ the item being deleted Thus, pop( ) removes an element from the given position in the list, and return it. If no index is specified, pop ) removes and returns the last item in the list. Consider some examples : pootd CH #2, 0, a Ut) | >»rellel = t1.pop(0) + emore element at index ie, ft >oelel clorent and store i in elet ” Ae The removed element >oott [ate 9, Bi qu] List afer remoning fist eement >>> ele2 = t1.pop() >ovelez + feo der specified, i will move v the last element >»?tL Cat, "et, Pa] The pop() method raises an except Tist is already empty. Consider this >>> t2=[] #empty list >>> t2, pop() 4 Trying to delete from empry fist Traceback (most recent call last): raises exception File “", line 1, in ‘t2.pop() Indexerror: pop from empty list COMPUTER SCIENCE WITH what if you know the value of ion = given Fosition inthe Hist? Well, Pye jot know its ine ethod ) emoved, not remove( ) 7 | loment to be removed, je the en iter from the Hist. Its used ag thought it in advance an vronce of iver item fr Per i -The removel ) method removes 1 first oF 1d does WOE TELAT hy, \ ! following format : essential argumient ®™ $ tig : uae nthe list. Consider some examples. “Ustrenove ( Individual ter and cetuns | tl.remove('k’) while remove searches for ay, | Valuetrror: list.remove(x): xnot in list Hem, and removes the fist i 7..The clear method matching item fr ete This method removes all the items from the list and the list becomes empty list after this function. This function returns nothing. It is used as per following format, List.clear() For instance, if you have a list L1 as | ooo Le [2, 3, 4, 5] pom Lisclear( ) {rs more all he items from lst Lt. >>> Lt [J 4 Now the ison ry te of wt is remove fom the tse - ip is removed frorn she Tsk | Unlike del statement, clear()) removes , lear() removes , . Alter clear(), the list object still exists as an e1 SFY the elements and not thelist element. 2 mpty list. 1 e count method = This function returns the count in the list it returns zero, It is used as per ui count ( ) For instance, for a list L1 =[13, 18,2 >>> Lindo [16) 0, 10, 18, 23] 7: UST MANIPULATION p> og” 71 why aze Usts called mutable types 2 4 wtat are immutable counterparts of uss? What ate different ways. of creating sts ? What values can we have in a list? Do they all have to be the same type 2 «, Howare individual elements of lists are accessed and changed ? 4 How do you create the following lists 2 4 (0) [4 5. 6) ) [21 3) (0 [-9, 8. 5) (@ [-9. -10. -11, -12) (0.42) 7 Ifa = [5. 4, 3, 2, 1, 0] evaluate the following expressions: (2) 2fo] ay (9 alafoy] ( apt-1y) (9 ala 2) +1) ) & Can you change an element of a sequence? What if the sequence is a suing? What if the sequence is alist? 4. What does a + b amounts to if 2 and b are lists 2 ‘1 What does a * b amounts to if a and b ae lists ? UW, What does a+ b amounts to if ais alist adbe$? isa string the same as a list of characters ? 13. Which funetions can you use to add flerents to a list ? 1. Wat ic the difference between append ) itd insert ) methods of list? 'S What isthe difference between pop ) sad remove( ) methods of list? 'S Whatisthe atference between append) ay, Mi emtend( ) methods of list? a How does the sort) wosk? Give example. does list. clear( function do ? ee. 9. The reverse method The reverse ) ‘everses the items of the list. This is done “in place’, fe, itd et ise ides not eeateaew is The syntax to “Ust.reverse() > ~ Takes no argument, returns ni list ; reverses the list ‘in place” Ani oes nol return anything For example, >>>tt 2's," 'p') >>? tl reverse() >otd + The raed tit UP ay 3g, We) >>> t2=[3, 4,5] - >> td = t2.reverse( ) 2 — apap, >>>t2 (5, 4, 3] 10. The sor! method The sort( ) function sorts the items of the list, by default in increasing order, This is done “in place", ic, it does Rot createa new list is used as per following syntax: List.sort() For example, >>> t1l=['e, >>> tl.sort() >> th Sorte ise in defaule ascending order (ae i, py‘ 'a] G, "a, 'd, ‘P] Like reverse(), sort( ) also performs its function and does not return anything. To sort a list in decreasing order using sort( ), you can write: ">>> List sort (reverse = True) vf [KOEN ‘tbe able to sort the values ofa, dw tues ofa list if ieee number as an element, jon has 10 ordering relation defined for mplex numbers. { Enter list : Given list is the minimum elenent of the <9 at index 8 Enter list : (7, 23, Given list is : (7, 23 ‘the mean of the given list is : 15.364285714285714 rent cen rom aise ot teen » progam fd mii ci" aot e eval dnpue( enter 1S Jength = Len(lst) min_ele~ ist {0 min_index =@ for Lin range(s i gases] < minele? Sinete « 15t(3] mnin_andex= 4 : a motven List 4s: "> Nininun element of the & ae ,min_index) ength-1) * print( iven list 15 3") print("The: i print(min_ele, “at index [2 3, 46-2) 6-7 Be [2, 34 4y -2, 6 7 given Tist 15 ¢ Progiam to calculate mean of a given list of numbers Ist = eval(input(“enter List :")) length = len(1st) mean = sun=@ for i inrange(®, length-1) sun-¢=1st[i] mean = sun /length print("Given list is :", 1st) print (“The mean of the given list is ) mean) 11, 55, 13.5, 20.05, -5.53 1, 55, 13.5, 20,05, -5.5] Program to search for an clement in a given list of numbers. Ast = eval (input ("Enter List :")) length = len(1st) elenent = int(input("Enter element to for iin range(@, length-1) : ifelenent == Ist[4] : be searched for :")) print(element, “found at index" i) break else Helse of f print(elenent, ‘or Loop “not found in given list™) COMPUTER SCIENCE Witt along, with its index In the tg, Sgt MANPUIATION net mple runs of above progra ‘ noe 'BFAM are being given below pise [2 Be % UL, $5, 24 rE Srenent €0 Be Searched for 1322" 78 67) me Faynd at index S wer fist # (2) 8 9 12, 55, -ayy tel Grenent to be Searched for ; zy"? 78 671 oot found in given list i {e count Frequency of a ven element in alist f numbe of numbers, Ast = eval (input(“Enter 14st :")) length = len(1st) elenent = Ant(input (“Enter elenent :*)) count = @ for i in range(®, length-1); if element == 1st{ij; count +=1 if count == 0: print(elenent, “not found in given list") else: print (element, “has frequency as", count, "in given list") Sample run of above program is given below : emer Vist : [1, 1, 1, 2, 2, 3, 4, 2, 2, 5, 5, 2, 2, 5] Enter element : 2 2has frequency as 6 in given list 1] 77 Program to find frequencies of all elements of a list. Also, print the list of unique elements in the list | and duplicate elements in the given list. | tepan Ast = eval(input("Enter list :")) length = len(1st) uniq=[] # list to hold unique elements duph = [] # List to hold duplicate elenents count =i=@ while i < length : elenent = 1st[i] count =1 t # count as 1 for the elenent at Ist[1] feet for Jin rane if elenent ** count += elset hen ent prane(vexenent”» c20 sf count 723! ; I “nig, appenacezenen®) os wd(elerent) vast 5 dup1append(elen sacorat tists : found in u vhen element $5 else: dad : saa {) sotements ace not print(*ordginal 14st) 188) | steer a print(-unique elonents List", unia) Toe on pring(“buplicates elenents 235%" dup) : | 72,9 2D 2, Bu 4, Sy By Gr 7s 34 See Enter Vist = Elenent 2 frequency: 3 Elenent 3 frequency: 3 Elesent 4 frequency: 1 | cronent § frequency: 2 ] Elonene 6 fresuency: 1 | ev\ Elenent 7 Frequency: 2 Element 1 frequency: 1 Element 9 Frequency: 1 original Tist [2. 3s 45 5, 3y 6, 74 34 Sy 2) 7p Dy OM 2] unique elenents list [4, 6, 1, 9] buplicates elements list (2, 3, 5, 7] Usts IN PYTHON = II

[['few", ‘words']}, this is a list with one clement, a list. () True. As Oth element of L[2: 3} list isa list [“few”, “words”] which hasa member “few" init. (¢) True. £{2] returns the list [‘few’, ‘words'], “few () L[2] = (Few, words’) an clement of this list. 12] U1] + U2) = [are’, ‘2, “fev, ‘words! 5. Lisanon-emply list of ints, Print the smallest and largest integer in L. Write the code without using a lop. Solution. length = len(L) Lesort() print ("smallest :*, print (“largest » L[@]) Lpength-a}) 7 LIST MANIPULATION ite the most appropriate Tist method to perform the following task. (a) Delete a given element from the tist, () Delete 3ril element from the list. (@) Addit an element in the end of the Hist, (d) Add an element in the beginning of the list. (2) Adi elements of list in the end of atist gatution. (@) Femove() (b) pop() (c) append) (d) insert() (¢) extend( ) 4, Given alist of integers, Ly write code to add the integers and display the sum. solution. pos = @ # start of list sum = @ # initial sum while pos < len (L) : # loop through entire list sum = sum + L(pos] # add current item to sun pos = pos +1 Hf move to next item in ilst print (sum ) # the answer , Given a list of integers, L, write code to calculnte and display the sum of all the odd numbers in the list. Solution. pos =@ # start of List sun=0 # initially no sun while pos < len (L) : # loop through List if L[pos] ¥2==1: # this is an odd nunber sum = sum + L{pos] # so add it pos = pos +1 next item in List print (sum ) # the answer 9, Examine the following code : Y nunlist = eval(input( "Enter list:")) pos = 0 odds = evens = @ Jength = len (num list) while pos < length : if numlist(pos] %2 == 0: evens = evens +1 else : odds = odds +1 Pos = pos +1 if odds > evens : print ("Balanced oddity") (2) What is this program calculating? (b) What does the program for thelist (1, 5,2, 3, 6, 6,9]? (©) What does the program print for the list |2, 5, 2, 3, 6, 6, 9]? How can we fix this ? Solution. (2) The given code is checking whether a list of numbers is ‘mostly odd’ — ie, whether there ate more odd numbers than even numbers in the list. (b) Balanced oddity (€) The code prints nothing. This if odds > evens : print ("Balanced oddity") else: print (“Unbalanced oddity") because there is only one print statement, the fix is : COMPUTER SCIENCE Wit} if they have al least one member py for le sake ofthe exercise, write jy using, sans “Overlapped” 10. Given tay fists, write # program Hat ri nero bul otherwise prints “Sqnarated™, You may use the tion. . oe = eval input("énter 14st] :°)) Lista = eval (input ("Enter ist2 :")) lent « len(1ista) Jen2 » len(1istB) for a in range(lenl) : ele = listafa) ifele in listB : princ(“Overlapped") break else : , print("Separated” ; LL Write a program te find the second largest number of a list af munbers. ‘loop ends normally, not because of break © Solution, Ast = eval (input("Enter list :")) length = len(1st) bineese = secondbiggest = 1st[@] # though logically not fair for 4 in range(1, length): Af Ist[i] > biggest: secondbiggest = biggest biggest = 1st[i} elif Ist[i] > secondbiggest: secondbiggest = Ist[i] print(“Largest nunber of the list :", biggest) print("Second Largest number of the list :" secondbiggest ) 12. Write program that inputs ats of numbers aut shifts all the zeros to right and all uon-zero mumbers toe, of the list. Solution, Ast = eval(input(“Enter list :")) Jength = len(1st) end = Jength-1 print("Original list : ", 1st) iro while (4 <= end): ele = Ist[i] ifele=0: for j in range(i, end): Ast[i] = Ist[jsa) else: Ast[end] = @ end = 1 4¥ Istip! i 4 # if after shitting, a Consecutive @ shifted to current place Print("zero shifted : ", Ast)

You might also like