0% found this document useful (0 votes)
25 views80 pages

PSPP Unit 4

Chapter 4 discusses lists and tuples in Python, detailing how to create, access, and manipulate lists. It covers operations such as concatenation, repetition, slicing, and various list methods like append, insert, and sort. The chapter also emphasizes the mutability of lists and provides examples for traversing and modifying them.

Uploaded by

karmegavarunan2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
25 views80 pages

PSPP Unit 4

Chapter 4 discusses lists and tuples in Python, detailing how to create, access, and manipulate lists. It covers operations such as concatenation, repetition, slicing, and various list methods like append, insert, and sort. The chapter also emphasizes the mutability of lists and provides examples for traversing and modifying them.

Uploaded by

karmegavarunan2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 80
— List Tuptes, Dieton Chapter 4 LIST. » TUPLES, DICTIONARIES us 1S js a sequence of values. Th = # yements oF items. “Y can be of any type. The values ina list are am stele 3 ; » R2017) creating a List i jgeare several WAYS £0 create @ new list maples, rie simplest Way is enclose the elements in square brackets ({ and J). umple: Allist of four integers: (10, 20, 30, 40] Alist ofthree strings: [YJovita, Jesvita’Varsha'] Alist of different type; {/March’, 2017 '2.6'] ) Alist that contains no elements is called an empty list. It can be created with empty brackets, []. Example: empty = [] | 1 Alist that is an element of another list is called nested list. Example: [Dell', 2.0, [50, 100] Here, a list contains another list. {ig Assign list values to variables Polit values can be assigned to variables. sem solvingand Python Programming. 248 ioe Example: [vanilla ‘strawberry’, tango] siceoreame rie ers = [5110.6] p>>name = [Denisha'] iceoreames, numbers, me) ha’ varawberry’, ‘mango’ [5.10.6] [Denis nal >>>printl [vanilla’, ‘4.1.3 Accessing list elements ‘ ist i essing the characters ‘Accessing the elements of a list is same as for accessing or e that is using the bracket operator. he index. The indices start at 0. pression inside the brackets specifies # The ex outP Example: >> iceoreames = ['vanilla’, strawberry’, ‘mango'] >>>icecreames|0] ‘vanilla’ >>>icecreames[1] ‘strawberry’ >>>icecreames[2] ‘mango’ Negative indexing Python allows negative indexing for its sequences. The index of —1 refers to thes’ item, —2 to the second last item and so on. Example: >>>birds=['parrot','Dove', ‘duck',cuckoo'] >>>print(birds[—1]) Aa cuckoo c >>>print(birds[-2]) rood duck ealdsitay od conic >>>print(birds| 3 4 [-3]) Jsidéinsy 3 SMBY O! bongieer sd rr = List, Tu » Tuptes —< j: Dlustration ~ Dictionaries mt Fist Wist2pyy & y 209) e235) B CIABII ini'List pain LIS" panceNested list C=",C) Le in("B101 = "810 Ting int("B[1] = "5BL1)) Fn ="BI-1D) pant’BE2]="-BI-2)) up List A= {1 2, 3,4, 5] Bi, ‘CD By =[[1, 2,3, 4,51 (LAB 'C,'D, EN) (UST OPERATIONS e last | 421 Concatenation operation i them end-to-end. In list operands by linkin, tn other and produce a third Coneatenation means joining two ate two lists with eae concatenation, + operator coneaten list, f 4 >aa[1,2,3] >>b=[4, 5, 6] >>>o=atb >>>e Hird 250 Problem Solving and Python (So — 4.2.2 Repeat operation atenated Lists can be replicated or repeated or repeatedly concatenated with the a f =" The * operator repeats a list in given number of times, operator >>>] *5 4140 ° S>>[1, 2,3] *4 : (i 2 SS UbAse 12 heel The first example repeats [1] five times. The second example repeats the} [1, 2, 3] four times. Program 4.2: Illustration of list operations (listop.py) } odd=[1,3,5] even=[2,4,6] | ° A=odd+even print("A =",A) print(" A #3 =",A*3) Output: 1, 3,5,2,4, 6] | ere REED 6 1,3,5,2.4,6) 4.3 LIST SLICES } ‘An individual element of a list is called a slice. Selecting a slice is similu selecting an element(s) of a list. Subsets of lists can be taken using the slice operator with two indices in si brackets separated by a colon ({] and [m:n]). A range of items in a list can accessed using the slicing operator. Slicing can be better visualized by considering the index between the elemen's Table 4.1 List Index Position 2; B Rubber | Scale 2 =| SN risk isp i! p Program 4.3 : Illustration of li Zoi sp2birds=['Parrot’, ‘Dove: " speprint(birds[2:4}) duck’ eucko9) : pauek's ‘cuckoo'} ifthe first index is omitted, the sli Slice starts al tthe sp>print(birds[: 3]) [parrot ‘Dove’, 'duck’] beginning, fthe second index is omitted, the slice oes to the end. >p>print(birds[2:]) tiduck’, cuckoo") both indices are omitted, the slice is a copy of the whole lst. >>>print(birds[:]) [parrot ‘Dove’, ‘duck’, ‘cuckoo'] A slice operator on the left side of an assignment can update multiple elements. spot [a', Di 'c''d,e','f] st] =[x)'¥] >>rt fal, 'x','y,'4) ef] ist slices (slice.py) birds-[/parrot',Dove', duck’ cuckoo] flowers=['rose' Jasmine" lily] nestedlist=[birds,[flowers]] print ("Birds [2:4] = pirds[2:41) print ("Birds[:3] = "> pirds(:3) print ("Birds[2:] ="> birds{2:)) print ("Birds =", birds) print ("Flowers = flowers) . Pew nestedlist) print (""Nested list = Problem Solving and Python Progr: = ['duck’, ‘cuckoo'] ‘parrot’, ‘Dove’, ‘duck'] Birds[2:] = ['duck’, 'cuckoo'] : Dove’, ‘duck’, 'cuckoo'] Flowers = ['rose’, ‘Jasmine’, lily] aoe : Nested list = [['parrot', 'Dove', ‘duck’, ‘cuckoo'], [[tose', Jasmine’, iy) | 4.4 LIST METHODS Python provides methods that operate on lists are shown in Table 4.2, Table 4.2 Python List Method Method pCaIINE ea | append) | Add an element to the end of the list. Ss Briend) | Addall cements faite another is | insert) Insert an item at the defined index. Be [removed Removes an item from the list. j | popd, Removes and returns an element at the given index. a} | eteaniy Removes alll items in the list. i index() Returns the index of the first matched item. | count() Returns the count number of items Passed as an argument. | sort Sort items in a list in ascending order. | reserve) Reservelthe order of items in the list. [coy0 Retums a shallow copy of the list, 4.4.1 append The ¢ append method adds a new element to the end of a list. Example: >>>t=[al, bic] >>>t, appen d( ’) tla, b,c gy amming, - Wee co & eto" exam This 4.4.3 The ' Exal 4.4. The Pos Sy Hi List, 7 eT Pes, Dictionan ies extend 253 s tend method takes a jj. 4 f joes not return S an ary nod di any value Be a and app Is rend content en All the elements. This 0 the existing list. snl pert =['a', 'b', 'c'] ity Sert2=[d'.'e] p>otl.extend(t2) ppetl fab ic’ de] p>>t2 td’, 'e] Ta mis example leaves t2 unmodified, — a a 443 sort al ape sort method arranges the elements of the list in ascending order fxample: >>ot=[[d','c’, eb’, 'a'] >>>t.sort() >>at['a’, 'b','c','d’,'e'] 44.4insert i i i This it ir element/object into a list at the index position. The insert() method inserts an a method does not return any value but inserts the given element 3 Position. i i te be inserted. : is the Ind se awpere the eeds t0 : i ed jnto - obj is the Object '© insert obj n° the giveD list. amminy 254 Problem Solving and Python Programming ——— Ee Example: >>>Name = [/Suthan’, ovita’,"Varsha’, ‘Denisha’] >>>Name .insert(2, ‘Jesvita') >>>print(Name) ['Suthan’, Jovita’, Jesvita’, 'Varsha’, "Denisha'] “Jesvita’ index position 2 (j Here in a list Name, a new name “Jesvita’ is inserted at index ps 2(ieary place). 4.4.5 count(x) The count method returns the number of times x appears in the list. Example: pepaq['a', ppc] >>>print(a.count('p')) 4.4.6 Ten The Jen() function returns the number of elements in a list, Example: >>>Num = (23, 54, 34, 44, 35, 66, 27, 88, 69, 54] >>>print len(Num) 10 4.4.7 reverse The reverse() method Teverses objects of list in Place. This method does n any value but reverses the Biven object from the list, Syntax: U9 toghdy elf Sete ico OTL ligt hades i. gxample evvv 4.4.8 m4 The ma syntax: Examp 4.4.91 The m Synta Exan Li eR LWles Die roles lonaries ps po>Name = ['varshay, 285 po2Name.reversec)”)°¥i8, ebishy z>>print(Name) “donald ‘Suthan'y (suthan’, ‘donald ", Sebishal « ove, vargha i max shal] Ge, ay 3 we pe ar sacOD FETUS the Maximum value 4 from a list syntast sample? >>>Mark = [76, 87, 68, 85, 77) >>>print Maximum marks" ma Maximum mark: 87 (Mark), 44.9 min Tiemin() fanction returns the minimum value from a list. Syntax: Example: >>>Mark = [76, 87, 68, 85, 77] _ >>>print ‘Minimum mark:', min(Mark) _ Minimum mark: 68 4SLIST LOOP (TRAVERSING A LIST) f a list through each element o! i is s, process of £0 ch i eee no : Jements are processed within a loop. the P lea oe into the list which prints eac! computation is called a is used as an index i e end-1. This pattern of n Programming ps6) problem Solving and Python Syntax: for in >>for icecreams in icecreams: print(icecreams) c Output: 4, Tt fo vanilla strawberry mango 2. The ‘for loop’ works well to read the elements of the list. But to write or y the elements, it is needed to specify the indices. A common way to do tha combine the built-in functions range and len. : Proj Syntax: Here, Index is the positional element of a List. Example: >>>icecreams = [‘vanila’, ‘strawberry’, ‘ >>>for iin range(len(icecream)): print(ice cream[i]) ‘mango’] Output: vanilla strawberry ‘ mango ‘ pdate is to List, Tuples, Dictionaries foop traverses thelist. The 19 otge retums a list of indices i ime through the loop «> ee aopaas the list, 21 len meth, 'd ret a ROM 0 to 4 nn the number of elements in the © index of yo Net? MS the length of the list. the next clement is got. The print a for loop’ over an empty list Never runs the bi 1 body. forxin D1: print("This never happens.» ted list will be considered as a ¢i the nest d as a single element, The length of this list is four: =>>L-[Dell’, 2.0, [50, 100]] >>>print(len(L)) 3 mn 44: Hustration of traversing a list (traverse py) jist-['a'D'c','d'] print("List =") for iin list: print (list) prose? ‘A=[10,20,30,40,50] prnt("A =") for in range(len(A)): print (A[i]) B=(1,2,3,4,5] print("B =" fori in B: print (B[i}+5) Outputs ; tit [a 6,6] B,C, 'd'] ramming v B58 problem Solving and Python prog) fe one-ett | | | | 8 | 2) 10 4.6 MUTABILITY | ‘The lists are mutable (changeable), When the bracket operator appears on the «| side of an assignment, it identifies the element of the list that will be assigned, | Fig. 4. Example: } represe >>>numbers=[5, 10,6] | ‘Icecre >>>numbers[1]=5 | contair >>>numbers | has be [5, 5, 6] List in Program 4.5 ; Illustration of list mutability (changeable) used z birds=['parrot','pigeon','dove',‘owl','penguin’] of the print("Birds = " birds) Read birds[1J="duck’ birds[3]"hen! oral print(""After changing pigeon to duck and owl to hen") i print("Birds = ",birds) ES a Output: z . 47, Birds = ['parrot’, 'pigeon', ‘dove', ‘owl', ‘penguin’] After changing pigeon to duck and owl to hen The Birds = ['parrot', ‘duck’, 'dove', ‘hen’, ' penguin’) Bb n the lef, ed. 1 Vanilla? Sy Stawber eee) list Numbers —. [> eas a 5 Desc list Empty —> [_] Fig.4.1 State Diagram fig 4.1 shows the state diagram for icecreams, numbers and represented by boxes with the word “list” outside and the er ier ‘feeoreams” Tefers to a list with three elements indexed 0, 1 and 2 ea contains three elements. The diagram shows that the value of the second element jasbeen reassigned from 10 to 5, ‘Empty’ refers to a list with no elements. indices. Any integer expression ean be award from the end ist indices work the same way as strin; ue, it counts back ised as an index. If an index has a negative val ofthe list. exist, shows the Index Error. Rad or write an element that does not ST MEMBERSHIP ip operators in Python. They are used tO test whether itand not in are the membersh sequence “alue or variable is found in # or not. not. If the element 4 Min Operator Bcc 0 alist ot Nein an element 87 age False: \ ratol whether ue otherws lee, cs: neirit will roduce ™ . mming so) problem Solving and Python Progra Example: ‘la’. ‘stra erry’, mango" s>icecreams = ['vanilla, ‘strawberry’ "2 go") >>>'strawberry’ in icecreams True >>>'chocolate’ in icecreams False 4.7.2 not in Operator Bre aetinloperatorleveluatestio events w.coes not find the element in the ty otherwise fal Example: >>>icecreams = [vanilla’, ‘strawberry’, 'mango'] >>>'strawberry' not in icecreams False >>>'chocolate' not in icecreams True 4.8 ALIASING Aliasing is a circumstance where two or more variables refer to the same object. ‘a’ refers to an object and assign ‘b = a’, then both variables refer to the sam object. Example: >>a=[1.23] >>>b=a >>ebisa True In this case, the state diagram looks like this. sige with one a Z ‘The ass« ‘example An obje that the If the al program 4.6: list=['/ temp= print( print( temp. print print print Output: list Ten Aft list Te 4.38.1 Alia It is safe behavior Exampl S cht re Ast Tuph Dict ona the same list has two gig = ries he 12 sith one alias affect the othe, oe er +80 it is aliased, Changes The 8ssociation of a varia, example, there are two reper ith an obj GS Tens temp tet H called @ reference, i this ‘An object with more than that the object is aliaseg, Same object, Re Fefetence has mon #S more than one name, so we sy + Ifthe aliased object is mutabte, changes made with made with one alias affect tthe other, ora 46: Mlustration of ist aliasing aise a he list ang ist=['A''BC''D] temp-list print("list = ",list) print("Temp = ",temp) temp.append('E’) rint("After Aliasing") print("list = "ist) print("Temp = ",temp) Output: jot [AYBS C.D] Temp = ['A’,'B','C’'D] After Aliasing list= [A,'B,'C,D, I) Temp = ['A','B'C. D’ E} object. If the same {81 Aliasing with mutable objects ing with ; «1 atiaging when working ltis safer to avoid aliasing yr-prone: behavior can be useful, it is er anutable objects, Although this 2,3] >>>1[55, 2, 3] 4.8.2 Aliasing with immutable objects aliasing is not as much of a problem, For immutable objects like strings, Example: gineering’ ‘engineering’ a b It almost never makes @ difference whether ‘a’ and ‘b’ refer to the same string, not. 4.9 CLONING LISTS * Gloning a list is to make a copy of the list itself, not just the reference. ) ¢ The easiest way to clone a list is to use the slice operator. ¢ Taking any slice of a list creates a new list. In this case, the slice consists of the whole list. + (Che changes made in the cloned list will not be reflected back in the orignal list. Example: >eexcfal Die] Ds y=x[7] >>>print(x) [a', bY, 'c'] >>eptint(y) er [a,b 'c'] : ag Ola ~>>print(y) [rb 1c] enn (a, by, 'e}] Outpt 4.101 Passi list. I Exar Here The print("list =" list) print("Temp = ",temp) print("“changes in the ¢} temp.append(E)°Stwill not age print("list = "list) fect original list") print(""Temp = ",temp) output? list ‘BY, 'C’, 'D] Temp = ['A','B'C, Dj changes in the cloned list wil fo ill not affect original list Temp = [A','BY,'C, ‘D424 Dg op 1s of | MOLIST PARAMETERS eine passing a list & an argument actually passes a reference to the list, not a copy of the jst Ifthe function modifies the list, the caller sees the change. Example: def delete_head(t): del t[0] ‘ frst element from a list. Here, delete_head function removes the fi ar ‘>>>letters = [[a', 0 'C] >>Sdelete_head(letters) >>>letters [b, 'c'] Treparameter ‘t ‘and the variable le 4 stters are aliases for the same object. on Programming problem Solving and Pyth 264, list © Differes 5 and + operator are, the appen ference between append method i Pe ’ HScifes ne + operator creates a new list. tg ocfis alist, but the perator cr Example of append: >>>t = [1,2] >>>t2 = t]append(3) >>>4 [12,3] Soot None The return value from append is None. Example of + operator: S213 = tl + [4] >>>tl [12,3] 28 11, 2,3, 4] The result of the + operator is a new list, and the original list is unchanged. ° The tail function returns all but the first element of a list. def tail(): return {{1:] This function leaves the original list unmodified, >>>letters Ta’, bi, 'c' >> rest = tail(leters) HUM San eset ately tv att bin >>>rest [b, ‘cl _————— ‘res’ is elemer An op each o 4.11.2 Filter Exan The « the uy « capitalize_all function take capitalized strings. ES a list of defcapitalize all(t): res=(]) for s int: res.append(s.capitali return res Par) ves is initialized with an i i ere empty list. Each time through the loop, i 4 t, So ‘res’ isa vena a tie loop, it append the next an operation like capitalize all is called a ma ma P Ls because it“ tach of the elements in a sequence, i ol ainonrolo a function onto 41.2 Filter Filter operation is to select some of the elements from a list and return a sublist. ‘that contains only upper’), 4p 99 i ae 6 problem Solving and Python Prog y od that return est tains on} e if th pe 2 earns ed a filter because it selects PEE supper is a string met uns True i Tetters. An operation like only_upper is call elements and filters out the others. 4.11.3 Reduce siti - slements into a single value jg . An operation that combines a sequence of Cee 'S cay | reduce Example: The add_all function, add up all the numbers in a list. def'add_all(: total =0 for x int: total += x return total total is initialized to 0. Each time through the loop, x gets one element from the jy The += operator provides a short way to update a variable. This augments assignment statement, total += x is equivalent to total = total + x. As the loop runs, ‘total’ accumulates the sum of the elements; a variable used thi way is sometimes called an accumulator. Adding up the elements of a list is such a common operation that Python provide as a built-in function, sum: >>>ts [1.2.3] >>>sum(t) An operation like thi , is that combines a sequence of elements into a single valt* sometimes called reduce, 4.12 DELETING ELEMENTS There are several wa Sto delete elements from a : ‘he YS to del mi it “ i a pop x 2, del {f the i elemer 3. rem To kn The x 4. de To x Calleg e list. ented d this vides Jue 8 port =['a','b','c] S>>x = t:pop() apt pa Dox ie es the list anc modifi and retums { A as removi ed, a) index of clement to be di r fa atthe removed val deleted is not provided, it deletes and ic 1S not needed, then the del oper ind returns the last ator is used. cement poet = [aly BS 'c'] >>>del t(1] >t fae j.remove (but not the index), the remove method is used. qpknow the element to be removed soot = [a,b,c >>>tremove('b') >>> (a, 'c'] Thereturn value from remove is None. 4del with slice : : than one element, the del pth slog index is wed emove more oO ¥ > "b! ‘c', 'd', te, 'f] i polls Pee gana ee ae igs pdt 8 _ atrix In this example, the slice selects all the elements up to but not inc ding the seq, pe i sr index. d Program 4.8 : Illustrating deleting 4 List (delete2-Py) P, aor list=[ABYC)DYEVFY OT pl 3,61 rint ("L list oa pop(3) 4 oor 5 print(""After deleting one element") N print("List = "Jlist) print ("Deleted element = "-%) del list{5] print("After deleting one element using del command") print(""List = "list) list.remove(A') print("After deleting A using remove command ") print("List = " list) del list{1:3] print("After deleting elements using slice") print("List = ".list) fi Outpu Output: List= ['A', 'B','C', DE F’, 'G] After deleting one element List= [/A\, ‘BY (CBSE GI] Deleted element = D After deleting one element using del command List = ['A',BY,'C, EF] After deleting A using remove command List = ['B','C’, 'E’, F'] After deleting elements using slice List = [B','F'] 4,13 MATRIX USING LIST f A list inside another list is called ‘ : nested list i ix represented with a list of lists (nested list). sauae he Seg, On, id Li SET ples, Di qrix could Be created wig, —etatles M=(U5, 4,71, [11,3 6 a > 6h 18, 17, RESET is 5, M(OJE] i gto) = 184) ana go gj and [8, 17, 9 on ee 1. Each row ¢ ae ™atrix sopra ws fr ogy M cont: 8 thee values pa three rows as [5.4.7], M= (6471, 11, 3, 61,8, 17, 9 gor iin range(3): for j in range(3) print(M[iJ[j],"\t") print("\n") et 44 TUPLES sequence of values, which can ‘be of any type and they are « A tuple is a indexed by integer. Tuples are an immutable sequence "defined, it cannot be altered. Tuples and lists are essentially the same. The imp tuples are immutable. A tuple is a comma-sep' ='a', 'bi,'c,'d)'¢ itis not necessary €° ea tuple is ‘of elements. That is onc ortant difference is that arated list of values. enclose tuples in parentheses: roblem Solving and Python Programming fre es Se | Example: ppetl ='a', | >>>type(tl) >type((2) 2, A tuple can be created using the built-in function tuple. It can create a en, tuple with no argument. Example: >pot=tuple() >t O 3. A tuple built-in function can be used to create a tuple with sequence ¢ arguments Example: >>>t = tuple((computer’) Sot (e,'0' ‘mp Program 4.9 : Illustration of tuple creation (tuple3.py) TI=(1,2,3) print ("Tl =",T1) T2=(/A\B\y' 1 'D''E) 4 ¢ print ("T2 =",T2) al qu ir T3-(T, [Pencils sjyfsyn suarnato larce patie oe P mec 74 ae e Ada CAB Bea (2) qa (2 aad ‘Operators 1. Bracket Opers gre bsacket oper? sort =( >>>t{0] @ >>>t{1] a >>>t{2] e S83 y 2. Slice Oper The slice ope Example: oe Ce’, Sa Lup >> Ty a 1p gi= (1,23) = (A, BC, 'D, = i; 4= (As 243), [Pencit’, : qa (12,3) CAS BY eae DYE) we operators on tuple ‘stl Operator ape raeket operator indexes an element t. port (e'0s >prt{d] aes ‘e pot] . >>>t(2], supe eae m we sggmrant ap ‘ >1[3], | {ngleand oe bmn fines) beabien0e * Slice Operator Theslice a selects a range of elements. (23.0) jemmt ae 0 ents in the Je tuples ¢ cannot be modified: ati WOZIEY rok AT ett assignmen element! gookaare ang and Python Programmi 272. problem Solving and Pythe 81 But tuples can be replaced with another tuple. seote(C) +1102] >t (Cy, '¢, 0, ‘mi, pw " 3, Concatenation Operator Tuples can be concatenated oF joined them using + oF concatenation operat, Example: Pen',Pencil’ Rubber’) iEraser"/Refil) >>>T14=T2 >>>print(T!) (pent, Pencil’, Rubber, "Eraser, Refi’) >>>print(T2) (Eraser’, ‘Refil’) 4, Relational Operators «The relational operators work with tuples and other sequences. + Python starts by comparing the first element from each sequence. If they equal, it goes on to the next elements, and so on, until it finds elements ti differ, Subsequent elements are not considered (even if they are really be Example: >2>(5,8,2) < (5,10,0) True >>>(3,2,500000) < 3,8,5) True 4.14.3 Looping through Tuple Elements Hort al enamel 02 ol Ui 4 go elements can be traversed using loop control statements. The for 10°? iv i tuple elements. The loop prints tuple elements either in sepatl® a a MSiingiezs tron Nogque t'nasoh + Av _ oorweekdays = spriday’, ‘Saturd >>> for wd in w print(w sunday Monday Tuesday ‘Wednesday ‘Thursday Friday Saturday 4.15 TUPLE ASSI Assignment of tup the left side of the ‘on the right side. 7 of elements in the Example 1: >erT1=( >>>T2=( >>>print (10, 20, >>>prin (100, 2¢ >>oT1. >>>pri (200, 2 >>>pr (10, 2 The left side : ch value j “de are eval =a ipriday’, ‘Saturday (Sunday', % y) Monday, 7» Tustday, sor for wd in we ckday = ys: se print(wd) rece re sunday Monday quesday wednesday iursday Friday saturday us TUPLE ASSIGNMENT -ament of tuple is a us i seful feature i left side of the assignmer re in Pyth Bes nt oper: 1on. It allo ate ight side. The number Ba en bedciessi ened Se tuple of variables on ariables on the left sh oe values from a tuple ye same as the number ofdements in the tuple. frample 1: > TI=(10,20,30) >>>T2=(100,200,300,400) >>>print TL (10, 20, 30) >>>print 12 _ (200, 200, 300, 400) >5>71,12=12,T! # swap TI and T2 >>>print TL (100, 200, 300, 400) ide is @ tuple of expressions. right the Ti it Sl able. All the expressions on the rogramming Bis problem Solving and Pythom P Example 2: >>>a,b=min_max(abed') pea ‘y >>>b ‘a yn with the number of elements ing ‘The number of variables on the left must mate! tuple. Example 3: >ppa,b=1,2,3 ValueError: too many values to unpack >>>[x, y= B, 4] é ; Sx 3 vob noting ai Ow Spay 'ty inabmigemamgives ad 0) 208s 4 use of Dluonaetial eds ao 2atdeiey + t e The right side can be guy kang. of sequence (string, list or tuple). >>>addr >>>uname, assigned to uname, ‘After tuple Assignment A=20 Bp=10 TUPLES AS RETURN VALUES tions can alwa i une yys return only a single value, but by making that value a tuple, @ jnetion can return more than one value. 416 trample: ft quotient and remainder, It is inefficient to e time. The built-in compute both at the sam the quotient Dividing two integers compute the ae x/y and then x%y. Python can notion divmod takes two arguments and returns a tpte of two vale: q remainder. Tt can store the result as. atuple. t=divmod(13.4) e tuple assignment. ements separately us Fgmod(134)'» qt aati eigen 8 em Solving and Python Programming problem Solving 2 276 tum a tuple, The built-in function min_maxo ;, , an rel = nai sat and smallest elements of a sequence and can Teturn a find the largest = two values. def min_max(t): return min(t), max(t) and min are built-in fanetions that find the largest and smallest elemen, max a sequence, min_max computes both and returns a tuple of two values. Example: >>>def min_max(t): return min(®), max(t) >>>min_max((6,3,7,12]) (3, 12) >>>min_max(‘abed’) (ai, 'd') Program 4.11: Finding circumference, area of a circle with return value def circleInfo(r): =2* 3.14159 *r a=3.14159*r¥r return (¢, a) print(circleInfo(10)) Output: (62.8318, 314.159) 4.17 TUPLE OPERATIONS 4.17.1 len The len() method Teturns the number of items ina tuple. Le a goample a2 >> a 4372 mP phe mp0? are same. it jt will vetur pxample: > > > > =I > 0 = il 4.17.3 mz The max Example jor a p77 72=(100,200,3 eid) 490.500, S use, a t 2 tuple of ome C cane it will return ‘zero’, oth: ese FMomerrice RAW na ample? spp T1=(10,20,30)F >>T2=(100,200,300) Soe 73=(10.20,30) >ppemp(T1,12) ents of a A peromp(T1,T3) 0 >>pemp(T2,T1) 1 4j73 max. lue method returns its Jargest item in bes ‘the tuple. ‘fxample: se2T=(100,200,300,400.500) Python Programming 278 Problem Sol 4. count | imes ofan object Occurs in a tuple The count method count how many times of an obj ple Example: >>>T=(100,200,300,400,500,100,200, 100) -print(T.count(100)) 3 4.18 VARIABLE-LENGTH ARGUMENT TUPL © Functions can take a variable number of arguments. A parameter », begins with * gathers arguments into a tuple. ame def printall(*args): print(args) The printall function takes any number of arguments and prints them | * The gather parameter can have any name, but args is conventional Example: >>>printall(I, 2.0, 3!) (1,2.0,'3) * The complement of gather is seater. To pass sequence of valuss w: function as multiple arguments, the * operator is used. Example: The divmod takes exactly two arguments. But it doesn't work with a tuple. >>>t= (7, 3) >>>divmod(t) TypeEttor: divymod expected 2 arguments, got 1 But if you scatter the tuple, it works: es ample: ma £ >>>max 3 But sun >>>sur ‘TypeE 4.19 LISTS A © zip is: of tup! name. of teet Example: >>>s >>>t — >> ee (b', Ce’, Seq Use pot sum does not spesum(l 253) sgypeBror sum expested at most arguments, , got sts [AND TUPLES _ jg a Duilt-in i ‘ a Se tenet cuerpo ome ofthe Function nl ee sen oe cs c. The fers to a zipper, which joins and Gaee ce of teeth. ssmple? sors = abe’ (0, 1,2) spprips ) ‘peresult is @ zip object that knows how to iterate through the pairs. zip is in.a for loop: « The most common use of 280 Problem Solving nd Python Programming Example: >>>list(zip(s. 9) [ca’, 0), (b', D, Ces 2) ‘The result is a list of tuples. In the string and the corresponding ¢ + the same length, the result has the leno, ot his example, each tuple contains a char, Jement from the list. tr, If the sequences are no shorter one. >>>list(zip(Anne’, Elk’) (CA, E), Ca, 1), (a's )) Difference between List and Tuples ee ‘The main differences between lists and tuples are, «Lists are enclosed in brackets ({]), and their elements and size cay, changed, while tuples are enclosed i oe ipl ed in parentheses (()) and canngj, « Tuples can be thought of as read-only lists. Like list, to initialize a tp, can enclose the values in parentheses and separates them by commas, ‘4 420 DICTIONARIES AND TUPLES Dictionaries have a method called items that | lled items that returns each tuple isakey-value pair, ameammaaccatucnc® of uples, vi TO) I0b6 Aigiqis loops non: 1P A}gts ni x eon, [pICTION. 42) ‘The date of keys separate comma: Items i same O synta> Laem If the value Dicti ue List, 7, 2 Tay Wes, Dictiona es fi picTIONARIES Ee 281 phe data type dicti aa of keys and a set of valy, — under ma separated from its value ne The key. ping. It is a mapping b colon etween a set ‘Value pair i c ait is called a ») and consecutiv led an item, A key is jtems in dictionarie: tiona fe laries are unorder lonaty are enclos items are separated by ss aaonaeneneteas ed, so we may sed in curly brackets({}). Se ty not get back the data in the red th it e data initially in the dictionary. . commas. The entire items j s ina dict syntax: { Dictionary 2: value 2, key 3: value 3} , If there are many keys and values in di i i in dictionar value pair on a line to make the code easier to a ae ee ee and understand, Dictionary_name ™ {Key-1: Value_1 Key-2: Value 2, Key-3: Value 3, 3 Keys in the dictionary must be unique and jmmutable data type. A dictionary can be of any type- Dictionaries are ot sequences, dictionaries ate called mappings pecause these are like a ¢ allows to look up information associated with arbitrary keys- s ati ilue is called @ . The association of a key and a val Fach key maps 2 value. eo key-value pair. The values ry are neither nom jn a diction’! in any specific order. be element js stored 10 and rettiew rather they are mappings: Python collection that ed from the dictionary first elements second + The location that a” js no logical depends only on its Ke : aq by a partoulat he : =< getermined PY e te. pene an S fn a value '§ stored 1S sated ashing: a. Tc values nto index yee od of converting a Fa! 718 the 732s Ample: «1025 8" Ts cy nd Python Programming ee print (daily_temp) 71.8, ‘thu’: 73.2, ‘fr iM +186, {'sun’: 68.8, ‘mon’; 70.2, ‘tue’ 67.2, ‘wed’: Program 4.12: Illustration of creating #ereating dictionary (1:"Sunday",2:"Monday",3:"Tuesday",4:"Wednesday" snp, "Thay "Friday",7:"Saturday"} temp=dict( {'sunday':68.8, "Thursday':73.5,'Friday':76.9,'Saturday':89.5}) cse{'name']='Arun" imonday':70.2,"Tuesday’:67.3,Wednesday7) 5 cse['name']="Britto print (weekdays[3]) print("Temp = " temp) Weekdays = {1; 'g r : 'Sunday' 2. Thursday’, 6: 'Fri day! ys) Temp = {'sunday' ae Thursday’; 73.5, "Friday ME is Tuesday’, 4: "Wednestt!> 4 , monday’: 79,2 _aonday: 70.2, Tuesday’ 67.3, Wednest" : 76.9, ‘Saturday’: 89,5) ty': 67.3, 'Wednes 4211 Meth The d the nz Exan Met Dict (em dict Rx: List, 1 1 ples, Dictionari pictionary daily temp stor <* 283 stores :75.6,, week. Here, each temperaty he average t “ temperature for each day of the Say, , non’, etc-): SHTINGS are often uso sos iS ted wit if n Used as Key valuce th a unique key value (sun, eT lay':71.8, daily temps [‘wea"] Fig. 4.2 Dictionary daily-temp eating a dictionary ytd © end 1: Dietfonary using dict() function () function is ‘used to create a new dictionary with no items, Here “diet” is qe dict ofa built-in function. ename Fsample: >>>mech=diet() >>>mech B Nethod 2: Creating empty dictionary using § co ncaa eae to the dictionary 0 qccessing, and initializing Dictionary can be created u: (empty string), use square tictionary values. vraokets (I) wi KOS mminy 284 Problem Solving and Python Progra) 1a is created. Three pairs are aug. dt, re brackets like 0, 1 and 2; the Here, an empty weekdays dictionary ‘ val dictionary. The keys are inside the sq¥ Beenie located on the right side of the assignmen ictionary using literal notation Method 3: iteral notation with key-value pair. Dictionary can be created using I Syntax: key: value, key, value, ' directory-name The Keys of this dictionary may be either integers or one-character string», corresponding values may be integer code points, one-character strings ¢y * 8 OF thy special value None. Example: >>>Weekdays={"Sunday":1,"Monday":2,"Tuesday”: rsday"5,"Friday":6,"Saturday":7} >>>print(weekdays) Sunday’: 1, 'Monday': 2, "Tuesday': 3, 'Wednesday': 4, "Thursday’ 5 ‘Friday’: 6, 'Saturday': 7} ednesday":47y, 4.21.2 Adding items into dictionary To add items to the dictionary, the Square brackets are used, Example: SpPese=f} >>=print(ese) a} ~>ese['name'"Antony” >>>csel'age'|=18 >>Pese[height’]=261 4 >>>print(ese) rsbnolve >print(ese) fname’: ae tage’: 18, ‘height’: 261} spfor x in nen eselx]), name: Antony age: 18 height: 261 (n0PERATIONS AND erHops IN pic 286 Problem Solving and thon Programming for Dynamically Manipulating > Table 4.3 Some Operations. Dictionaries i ie pb g Be Creates a news . | | Cees a wit Ke) aloes lr RSS E | © |srera sequences tor exemple, AmullanAset es dict nit dag = } fruit data is (possibly read from file) to ! {feapples’,.66[.... bananas’, 497) _ ‘Length (num of key/value pairs) of dictionary d- | pens Gets the associated value for key to value, ee to either adap Aatkey} = value | jes yalue pair, or replace the value of an existing key/value yi y) = Jeldikey] _ | Remove key and associated value from dictionary d. 1. len funetion This function returns the total number of key-value pairs in the dictionary, Example: = >>>len(cse) : 4 2. in operator The in operator tells whether a key is present in the dictionary. Example: ; >>>'name' incse True >>>'Antony’ i False q 3. values finean iy _qred funtion 18 18d to sor e Keys ofa diction ary, ole pepstadents= Hany. ‘penisha'B+', ‘Suthan'1A_ Jovita’: =>>for key in sorted Ras nts); "OP," Sa HRS axa ee Fy as print("{:2} {3" 343" format(students{key) k Lkey)), pt Denisha Bt Harry ‘At Jesvita 0+ Jovita ‘A- Suthan B- Varsha keys function js function return This func returns the total number: ‘of key-value pairs in the dictionary. Fxample: >>>print(ese-keys()) dict_keys({name’, ‘age’ ‘theight']) USADVANCED LIST PROCESSING: LIST COMPREHENSIONS. rncise way to create s an elegant and co! new list from an + List comprehension is existing list in Python. + List comprehension can be characteni2s described by a series of keywords: jn list if expt] pea roces, DH PIO is [expr for vat jist is a0 existing sequence: sion that evaluates true OF false. python Programming 288 problem Solving and. : s each element in the original iss st, the initial expression iS evaluate 4. ct the new sequences t eorvowels=( «To constru it sf expression te xpressic uateg ane : es to the new list. In this fashion, the list cong oe rolls combines tbe aspects of PO BAIT anda? nt lie es ; «List comprehensions are ‘often used 8 the poy st a actos me AG definition provides # convenient syntax and a WAY 10 Dov en , fanguments. The list comprenensior is an easy 10 understand ang «98 vepevowslss ! debug way to write he body of De function. _ 5: | s>pdef listofsquares(@): psample ! return[x*x for x in al ei. <> (ali fc 1.3.5) >>olistofsquares((6.49)) [36, 16, 81] program 4.13: Example 1: i r ‘ithout ‘The range fimetion allows) tie Beneretionyof Sequences of integers in fay e Pe increments. por € print(" SSSLe[xh'2 for xin range(19)]} ppprint(L) [1, 4, 9, 16, 25, 36, 49, 64) Example 2: ery =[L,2,'a,3,4.0] Sa G0 oe en — 14,9] — 2 ato toman bp: irvinale G8 noiattortore This example squares the inte : sth a il anwar . — eee B ay ; 1 1 See alioile Ty ee oS 299 p77 tel s used for gene generating a list containing only th vowels in string t le vores is ple St 2,3,4,5) practh23" ‘or i in range(O,len(a)) if i%2 0) portal] 13-5] pga 134 jhlustration of list comprehension without list printing sequences comprehension. of integer ion") prini("without ‘using list comprehens problem Solving and Python Pro} ramming. 290 em ci, omprehension Program 4.14: Ilustration of list Fe ieee print(® Generating odd numbers") Bae computation i print(” Without using list comprehension’ a tation, 80m conintage of the d a-[1,2,3.4,5,6.7,8,9,10] pene js not known for i in range(0,len(a)): pene sgne dictionary i pa ipeosorie collect print(" Using list comprehension") es .2,3,4,5,6,7.8,9,10] exam) [i] for iin range(0,len(a)) if 1%62 0} en hi a print(b ) fo Output: | Generating odd numbers Without using list comprehension 1 Hl t / 5 u . 9 The histogram Using list comprehension string. Each ti U1, 3, 5, 7, 9] creates a new dictionary it in 4.24 DICTIONARY AS A COLLECTION OF COUNTERS ak Example: lere are several ways to . . : Some cftenay #88 10 cout Row many times each Jeter appears inten a colette tt60s deh 1. Creat i >>>h reate 26 variables, one for each letter of the alphabet. Then travers t {pil string and, for each character, in probably using a chained conditional, 2. Create a list with 26 elements, the number as an index into th PRE lcrement the corresponding cout’ Then convert each character to a numbe.® fan Ierement the appropriate cou as keys and counters Y the character is seen at first time, add an" ‘the Value of an existing item, u fe options per ae " oo ae ferent way. an, omPutAto = a impler 5 i (Oe of the er va emetation i san aAIysimpleweacee®, PW Wika OEY. Gar a leon po eee nn others, For example, an Bs y makes tht, even ifthe mint an be letersappeat in the but each of them implements , Fi m for crionary implementation uses (h Ne letra ogee Te lection of e« le fun for aco counters (or fy ‘ction histogram, which is a statistical Fequencies), i ample jpodef histogram(s): ict) for cin s: ife not ind: dfc]=1 else: d{c] +=1 return d se bistogram function creates an empty dictionary. The ‘for loop’ traverses the aang, Bach time through the loop, if the character ‘cis not in the dictionary, it cates a new item with key 'c! and the initial value 1. If 'c! is already in the feionary it increments dlc) suumple: se>h-histogram(‘parrot) >>>h (pia Lt 2,702 b that takes @ Key and a default value. Tf the otherwise it nding, values d called “get” . the cosresPot Dicionaries have a metho returns {ey appears in the dictionary “get Teums the default value- DICTIONARIES ina gictionary, ney SSLOOPING AND thon Programming y Solving and P) ns Problem Examph ing value. print_hist prints each key and the corresponding ¥ def print_hist(h): fore in h: print (h{c]) Output: >>>h = histogram(parrot’) >>>print_hist(h) Here, the keys are in no particular order. * To traverse the in sorted order, use the built-in function ‘sorted’, {rol oN jyrmncitsa its Example: att % PSE Sintihe berthed Bald lis, Sorted(h): Ticaawls i i > forkeyi ins Lis oe St Tues, times=n ctionarieg while(times>0); = output times=times.} Print(outpue) pistogram([6,13,6.25,18}) wip eee PEEP see pee OR OE EOE ees ee RH OE EOE goerse OOKUP given a dictionary ‘d? and a key ‘k’, it is easy to fi {hj This operation is called a lockup to find the eoresponing value v = » Tofind value ‘v’ in dictionary ‘d’, there are two possibilities. | There might be more than one key that maps to the value *v’. Depending on the application, we can select one, or a list that contains all of them. 2. There is no match between sy’ and ‘k’ and the value *v’ is not in dictionary “d’, This is called reverse lookup. that maps to that value. * A function that takes a value, returns the first key def reverse_lookup(4, ¥): i for k in d: qumerica if d{k] =v: return k raiseLookupEsr0r0 a aise statement causes 28 7 ater. an used to, hs finetion is an example of the ca sghich isa built exception : pe on; in this case it causes alee that a lookup operation 1°” Problem Solving and Python Programming 294 If the loop reached the ‘end of the loop” that means ‘v’ doe, dictionary as a value, so it raises an exception. Example of a successful reverse lookup: >>>h = histogram(‘parrot') >>>key = reverse_lookup(h, 2) >>>key fa Example of an unsuccessful lookup: >>>key = reverse_lookup(h, 3) ‘Traceback (most recent call last): File "", line 1, in File "", line 5, in reverse lookup LookupError >>Praise LookupError(‘value does not Traceback (most recent call last): File "", line Tin? LookupError: Value ‘reverse lookup is much Cletionary gets big, @Ppear in the dictionary’) 085 n0% appear in the dictionary slower than a forward ee the performance ‘ehh iP. If it is done often, orifte rogram will 0 Boathion: The selection sort se, element is found, it ig pample:56, 91, 35, 72, 48, 6g unsortedlist 56-9 ‘AfterPass2 35 [py argument. AfterPass3 3548 48 After Pass4 35 After Pass 5 35 48 Sorted List 35 48 Program: ften, or if the ‘kfselectionSort(A): for i in range(len(A) —1,0, -1) max=0 for in range(1,i +1): if Aj>A[max]: the element is found, itis gy, «This process of selection | + Then the second smatjeg pe | the list have been sorted in as, After Pass | so 3 smallest clement i ce in the list. When the ath al elergeae heli then searched, When the ‘lement in the list until all the elements in. ol 7 Ro ———_ Problem Solving and Python Programming print(Enter numbers’) fori in range(0,n): X/ij=int(input) selectionSort(X) prini(X) Sse: RB Hers Palace boooae or gas | Enter list size: 6 | Enter number until all the elements h; ‘ ave be Insertion Sort Pao aae Performs of n - 1 ee on ~ I passes, na Pass P = | through nel, inserti X=[0,0,0 n= int(in print(‘Eni for i in re X{i}- insertion print(X) Waononm [Ss lo re issrtionsortA): fori range(1,len(A)): ‘currentvale = Afi] ition =i ‘nile position>0 and Afposition-1}>c ‘Afposition]=A [position 1] era position = position 1 ‘Afposition]=currentvalue 0,0.0.0 =H 5-{0,0.0,0,0.0. ining Enter ist siz =) numbers’) problem Solving and Python Programming y 298, Oe ee RN | mi Merge sort uses divide and conquer method. The problem is divided jg problem and solved recursively. Finally it merges two sorted list. sg | Basie Algorithm | i. Divide the given array of elements into two half, | ii, Recursively sort the first half and second half of array elements | iii, Take two input arrays A and B, an output array c iv, The first element of A array and B array are compared, then ¢, smaller element is stored in the output array C, the correspondin, pointer is incremented. ng v. This step is repeated until all the elements are compared. Example: 2413.26 B Pea gi0G 3) ne a eis 2 ; [ ao 5 a a 2B | [os L Es a ~— X= [( oes sin 27 Ft . Ia ey Pin sey) [ee ‘or i in 2 am. Lae xi mh merge if 8 4 SB Print(, a 1s ” ———— Program: Outp, def mergeSort(A); Enter iflen(a)>1; Enter mid = id= len(Ay/2 8 lefthalt 2 tighthalf = ihthalf'= mids) 3 3 ( a List TUples, Diction onaries a —peraeSorilenthally Say tperaeSort(righthalf) vided into s-—<| e smatie i . By i 10 ile isten(lefthald) and j = pivotvalue and r : rightmarko= I rightmark = rightmark -1 Se if rightmark Greater than pivot Less than pivot Pivot | BLT oi nt Boy, | | def histogram( items ) for n in items output =" times =n. while( times > 0): output times = times 1 print(output) histogram({S, 3, 8, 4, 6, 10)) peneeee senses seeeeeners 6. Student Mark Statement mark = [] tot=0 students=[] grade=[] num |~int(inpui("Enter number of students: ")) for num in range(numl): x=input("Enter name of students: ") Students.append(x) Print("Enter Marks for i in range(s); mark.append(input()) Obtained in 5 Subjects: ") for iin range(5): tot =tot + int(markfi]) avg = tot/5 print("Name= "x) ifavg>-91 and avg<=109- Print("Grade = Al == g and Python Programming: ing a Nam Enter Enter so 8l and avg<9]; ie vir Grade = A2") ee yern71 and ave=21 and avg<33: print("Grade = E1") else: print("Grade = E2") Output: Enter number of students: 3 Enter name of students: Arun Enter Marks Obtained in 5 Subjects: Grade = Al ‘ Enter name of students: Rant Enter Marks Obtained in 5 Subjects: GROEN BTA WH YET q List, Tuples, pj we ctionaries | orl and avg<9]- 1( © print("Grade = A2) a0 gifaver=7! and avg=51 and ave<61, |) print "Grade = C1") || gifavg>=4l and avg=33 and avg<41; | print("Grade =D") elif avg>=21 and avg<33: print("Grade = E1") else: print("Grade = E2") Output: Enter number of students: 3 Enter name of students: Arun Enter Marks Obtained in 5 Subjects: 98 97 96 51 95 Name= Arun Grade = A1 Enter name of students: Rani Enter Marks Obtained in 5 Subjects: B 15 84 9 89 - ene el eee SS Enter Marks Obtained in 5 Subjects: 64 SI 46 47 52 Name= Madhu Grade = C1 7. Retail Bill Preparation tax=0.18 Rate={"Pencil":10,"Pen":20,"Scal print("Reiail Bill Calculator \n") print("Enter the quality of ordered item :\n 2) Peneil=int(input("Pencil: ")) Pen=int(input("Pen:")) Scale=int(input("Scale:")) A4paper=int(input("Ad Paper:")) Writingpad=int(input("writingpad:")) costPencil*Rate["Pencil"}+Pen*Rate["Pen Adpaper*Rate["A4paper Bill=cost+cost*tax Print("Please Pay Rs. %f" % Bill) Output: "Adpaper":165," Writingpad’:15) '}+Scale*Rate["Scale"}+ 1} Writingpad*Rate["Writingpad"] Retail Bill Calculator Enter the quality of ordered item : Pencil: 5 Pen:7 Scale:4 A4 Paper:3 writingpad:2 Please Pay Rs. 876.740000 a Phor Al ¥ i J pat Enter number of 7 antange n+l): acl Feininpat(’Enterclemen . gappend(b) » Ments:")) for] in 5f§%2= -0): even.append(j) else: odd.append(j) ai("The even list",even) pin(The odd list"004) Output: Fater number of ‘elements:5 phonebook=dict() ((input("enter total m parle e nh print("Name","\t,"Phone number") for i in I prin Outp jonebookfi)) Enter total number of friends5 enter name Varsha enter phone number —_— 9868734523 enter name Denisha enter phone number 9934567890 enter name Ramesh enter phone number 9678543245 enter name Jemima enter phone number 9877886644 enter name Raj enter phone number 9655442345 Phonebook Information Name Phone number Varsha 9868734523 Denisha_ 9934567890 HH Ramesh 9678543245 Jemima 9877886644 Raj 9655442345 newlist = [] for number in numbers: iftumber not in newlist: newlist.appen Prinnewiisy, Perum) Teturn newlist remove _duplica tes([ 12345,55,6,3,2) Problem So and Python Programming ara ee ee Oe ee sen ee Ti fi ar i if con an array of number g 7.0,0,0,0.0,0,0,0) ov einpul(Enter a Dumber: » 4 center n numbers’) » Ain range(0.n): g-int(input()) joc iiaamge(Onn): om-sum+ ALi] (sum= sum) pt Output: pote a number: 5 ater n numbers 1 2 3 4 5 sum= 15 [SSorting numbers in ascending order = ‘4=(0,0,0,0,0,0,0,0,0,0} sum=0 1=int(input("Enter a number: ")) prin((Enter n numbers’) fori in range(0,n): AliJ=int(input() ‘bri in range(0,n): forj in range(i+1,n): if(ALiPAL): temp=A[i] — ALIFAG] AljJ-temp for in |, Attia: ie Print(‘The maximum element is= brint(‘The minimum element is=' Output: 2 34 >. ee. a — elt Enter a number: & Enter n numbers | and Python Programming Problem Solving Enter n numbers n= int(input("Enter a number: ")) print(Enter n numbers’) for iin range(0,n): Ali-int(input()) 0] [0] for iin range(0,n): if{A[i]>max): max=A(i] | fori in range(0,n): ‘f(A Li} Srtl23456] to use the “ list itsere ov! Dee 2022, 2021) ice apc lt not erate US the ref ' reference, The sll] 7 int) 7 me 3,4, 5.6] co! sist are the valu * es of tuples accesseq? ate with m1 les accessed? Must strate with an exay ple, (AU No Nov/ Dec 2022, R2021) oacvess values in tuple, us » use the s quare brackets for slicing al g along with the index arindices to obtain value avai pxample: available at that index. TI=(1,2,3,4,5,6.7); print("T1[0] :",11[0}) TIO]: 1 print("T1[1:5]: ",TI[1:5)) TI[l:5]: 2, 3,4, 5) yutable objects. i Give examples for mutable and imm (AU Apr! May 2022, R2021) Refer Page No. 112 (AU Apr! May 2022, R2021) ary in Python? e data values in pairs, A dictionary isa d do no' key : value { What is purpose of diction: ¢ allow duplicates. Dictionaries are used to stor callection which is ordered, changeable an Jues stored ina list are accessed” (AU January ta type? they ca b Should the elements 2022, R202) ‘Inpython, how the val ‘fa list be of the same dat Alistis a sequence of values: : A list of four inters: [10, ab, ee pe list of different types! [eMareh!s e any TYPE i red collection of da ae re dictionary holds key : y 110 song is an 5 Dictionary in python is alu Jnlike other dat values like a map. Unlike oth +2: ‘For’, 3: ‘Every day”} Example: Diet = {1: ‘python’, 2: “For, Can functions return tuples? If yes give example, 7. Can functions retur AU Nov/Dec 2015, yy tein funtion min max) is yyy) fa sequence and can return ca m a tuple. The A funetion can returt the largest and smallest clements of values, Example: >>>def min_max(1): return min(t), max(t) >>>min_max({6,3,7,12]) G12) >>>min_max(‘abed!) (a, 'd) 8. Relate strings and lists. (AU DeeiJan 2019, Rain [Sino | Strings pRB Lists |. _| String is a sequence of character is alpha numeric Adding value is not possible Adding values can be possible Values can be changed Access values from string Access values from list Removing valuesis not possible _ | Removing values is posstle first key mapping!! (AU Dec/Jan 2019, RM dictionary = { 1; {'name': John’, ‘age!: 27}, ‘. 2: {’mame': ‘Marie, ‘age’: 22}, 3: {'name': ‘Luna’, ‘age’: 24}, {'name': ‘Peter’, ‘age’ 29}} Search age t(input("Provide age :")) for age in diction, ary values) t eh i i if pri is a list? what is a list? 10- ‘a list 8 @ Sequen pxample: 12,345, Be -qhe main differ 11.What is list? ¢ ‘A list is a sea called elemen Example: a = 12, Why list is a A list is also from the list < 13. What is me: Aliasing is a If ‘a’ refers Object, Example: SSE >> p- Pdi a List, in UPles, Die if age search age lonaries print(age) 2 Y 2022, Ro, sed to ee aynat isa Hse? HOW Hist ary vali wf alue pair, risa sequence Of Values, Tom tuples? peer © They can be of, (AU Jan 2018, R201 ample ‘any type. ahi 4, 5, 6,7, © 2019, Ro yah} 7,8,9, 10) 017) | ge ain differences between Tiss ang and tuples are: is used to 3 tuple ed Sa : eae enclosed in brackets) Freinyelements and size oan bo snot be updat changed hats ist? Give example. tis a sequence of values. The ¥y can be any type. The values in a list are ‘aed elements oF sometimes items sample: 2 =[10, 20, 30, 40] 2019, R2017) See DB wiy ise ls a dynamic mutable type? ymeric Alist is also a dynamic mutable type because we can add and delete elements ssible fom the list at any time. aie | ___ | J What is meant by aliasing? refer to the same object: -more variables to the same stance where two oF then both variables refer Aliasing is a circumst If‘a’ refers to an object and assign b= problem Solving and Python Programming 320 14, What is meant by cloning’ i copy of the list itself, not just the reference, yy, Cloning list is to make a cOPY ea =~ way to clone a list is to use the slice ope*2°% 15, What is Tuple? Give example. © Tuples are an immutable sequence of elements: That is once, , defined, it cannot be altered. «A tuple is a comma-separated list of values. WD >p>t='ai,'bi,‘c', ‘di, 'e 16. What is dictionary? A Python dictionary is a group of key-value pairs. The elements in ee are indexed by keys. Keys ina dictionary are required to be unique. ay 17. How can you access data from a dictionary? The simplest way to retrieve a value from a dictionary is by with a key. To get a key's value, just put the key in bracke of the dictionary. directly accessing, ts, following the ny 18. What is the main use of a dictionary? The main use of a dicti is ie ictionary is to look up the value Associated with a partiolx dictionary essing it the name particular ction that es (0) scribe the addi ser dition ang examples Md dete pefer Page N 249 t data str ture with) (AU Novi | ite @ FOBFAM that has ai ® rails. Tet to stor © topper deta 1s and display the -.. ae play the sos the Basic tuple operations a pefer Page No.: 269 mi evamples. (a U Novibes 2022, R2021) a program to's¥ap tw values Using tuple assignme P tWO values using tuple a signment prefer Page No.: 273 (AU Nov/Dec 2022, R2021) ea Lists. How to add elements to the lists? Expl th example program. he lss? Explain with a suitable Fefer Page No. 252 (AU Apr/ May 2021, R2021) ‘bble sort algorithm using python programming. « Explain bu (AU Apr/ May 2021, R2021) Refer Page No.: 307 .4 on a list and outline any four with an 1, Name the operations that can be performe (AU January 2022, 2021) example. Refer Page No.: 249 ‘ : arate ereate, 200es8 concatnste TN 1 Write separate python program CE (AU January 2022 R2021) delete operations in tuple Rater Page No 269 ong ‘n” randomly gqnerate “f it maximum am a0) 9. Writ rogram, print the » rite a python prope” ist. cau Novdes 2019, R2017) fumbers by storing them 0 thon Programming problem Solving and Py! w2 Progra import random i def Rand(start, end, num): A-O) for jin range(num): "h append(random.randint start, end) A.sort() print("The Numbers are") print(A) max=A[-1] . print("Maximum in a generated numbers is : ",max) num = int(input("Enter number of elements to generate :")) print("Enter starting and ending number to generate random numbers" ') int(input("Enter starting number") t(input("Enter ending number") print(Rand(start, end, num) star Output: Enter number of elements to generate : 25 Enter starting and endin, ig number to generat Enter starting number60 oo Enter ending number120 The Numbers are (63, 64, 67, - 71, 72, 74, 76, 76, 77, 78, 78, 78, 82, 90, 92. 100, 106 11,1 ieee | 7 006,111; 111, Be 118, 118, 120, 120, 120] faximum in a Senerated numbers is: 120 10. Define Dict Onary in Python, Do the fo} ‘Owing operations a i : ing A . th On dictionaries. i Initialize two gicys . dictionaries wi i Compare th es With key and ; © {Wo dictionaries wa, Aue Pairs. aes With master Key list and print missing iii. Ring key i : i "YS that are In first and not in Second r tar ‘ond dictj a ictionary, Merge tio dictionaries 5 and create a new dictionary usi ing a sind (6) ize tWO dictio, ionaries, S With © oer: pot = CROIINO! 1M iota = {ROIINo': CSOs. pa DIEIONATY 1: Ft Dietionary 2: output: pictionary 1: {'RollNo';» a} » Name's "Murat picionary 2: ('ROIINo': ‘gE 5 all, "Dept: Mech’, ‘Grade "Name': = Athi compare the t thi, Dept: ‘se, Grade:'C wo dictionari ies wit with master key list and ist and print missing keys, program: pietl = { 'RollNo': 'MECHOT ei pict2 = { 'RollNo': “CSEDS, Nonna Nt Det Me "Grade: | diff set(Diet2) - set(Dietl) ee print("Missing Keys: " diff) ai Find keys that are in first and not in second dictionary. ‘A Program: Dictl = { "RolINo': 'MECHO!’, ‘Name’! Murali, 'Dept’Meeh, Grade Dict? = { 'RollNo!: 'CSEOS’, 'Name'*Arthi’, Dept ese’) for key in Dictl-keys(): ifnot key in Dict2: print(key) 111, missing Output: Grade , Find same keys in two dictionaries. single Pi n Programming. a a vingand Python PF af n solving a sroblem 324 ‘Dept':'Mech’, Program: ‘Name!/Murali’, ‘Dept! 1. MECHO!', ‘Na ', ‘Dept':'cse'} ct] = { 'RolINo': ME fame’“'Arthi Be {RolINo' ‘CSE ie jiom(Diet2-keysO)) oe print(set(Dict1-keysO)-iP a Output: E “ ‘Dept’, ‘RollNo'} ee ea was Jereatea new dictionary USINE 8 Single expyg v. Merge two dictionaries and c 5A Program: i CHOI, ‘Name'"Murali’, ‘Dept'’Mech’, ‘Grader ict! = { 'RolINo!: 'MECHOI'’, 'Na ', '‘Dept':'cse’, 'Grade!"Bn es eee ‘CSEOS', Name'/Arthi’ ‘Dept''ese’, 'Grade'B)) jict2 = { ‘a Z x={**Dictl,**Dict2} print(x) 11. What is list comprehension in python? Expression with example. 6 (AU NovMee 2019, R201 5 Refer Page No.: 287 12. What is tuple in python? How does it differ from list? ( ip s (AU Nov/Dec 2019, R201 Refer Page No,: 269 13, Writ z Write a python Program to sort n numbers using merge sort, 9 1 Bi i Refer Page Nox 298 (AU Nov/Dec 2019, R2017) 14. Discuss the dj ; 3.2 % the different options to traverse a list, 8 (AU Dee/Jan 2019, R201” @ (AU Dee/Jan 2019, R20!

You might also like