0% found this document useful (0 votes)
3 views24 pages

Lists in Python

The document provides an overview of lists in Python, explaining their characteristics as ordered, changeable collections of items that can contain duplicates. It details how to create lists, access their elements using indexing, and traverse them using loops. Additionally, it discusses list types, including empty lists, long lists, and nested lists, along with the concept of aliasing in lists.

Uploaded by

srijarajesh274
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)
3 views24 pages

Lists in Python

The document provides an overview of lists in Python, explaining their characteristics as ordered, changeable collections of items that can contain duplicates. It details how to create lists, access their elements using indexing, and traverse them using loops. Additionally, it discusses list types, including empty lists, long lists, and nested lists, along with the concept of aliasing in lists.

Uploaded by

srijarajesh274
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
Lists in Python ral INTRODUCTION cur naturally in many it gequences 00 Wy real-life situations, A OPE ontheare anne » A year has 12 months (January, February... sisson Ti ate a @ sequence. After January, it will be roots itisimpossible ome a Wy bec Se it has to go in a sequence. So, we can say a sequence is an ect ie items of data. The items are stored in a sequenc: ter th cher, eg @ Sequence of events, movem: HAOR avi reco ents, items or a sequence i i (nase) with a sound recorder/sequencer. Consid ml aa sequence Sitar a mt + Consider the example of a sequence of cars, as shown infig. 7. item of this particular sequence. Here, we have a grey-colored car, a blue car, a red car and so on. So,all these cars combined together form a sequence. Python also supports sequences which can be considered as containers and in those containers, certain items are stored. A sequence may tave repeated items in the list. The number of elements is called the length of the sequence. The vatious sequences available in Python are shown in Fig. 7.2. Fig, 7.2: Sequences in Python @ scanned with OKEN Scanner ‘In this chapter, we will focus only NTT" fn successive chapters ae ed 7.2 UST values /items. The element mn ordered sequence of values/items. Bay ‘Alist s collection of values or a8 oF ' eerie ‘be modified, which means that Python will not creg tS * Like a string (sequence of characters), lst is also a sequenced data type. “CIMA iva colection of comma-separated values hems) within square brackets. ems ita not bef the sme Pe 1.21 betainreaingaatng Ut Lise canbe crested by puting commaceparated valua/ems In square brads Seure aches eae the sar and end of the it, constng of elements separ comma Uist elanentsy/ems are ordered changeable and can be repented Inderes ae cso secs he tems The syntax for creating a sts ‘dist, sane> = 1 For example, 1) Fist Display consteuet ‘The given constructs termed asa List Display Construct. Square brackets in the given son Contain a set of values/elements constituting the list with the name given as ‘This is termed as intillzation ofthe list. A list having no values is called an empty list an be populated with any type of values/collection of items by enclosing them in 3@ of values/collection of items by enclosing square brackets [as shown inthe following example. Inthe gven example, we have a list items—CS,1P and English, sey in square brackets [}, List Types and Examples: Learning Tips Make sue strings are encosed in sae! double quotes while dec? them ast ema, Pe cannot difereniate bev flngle or double quotes. 5° °° can use whatever we wort of Subjects having three arated by commas and enclosed Usts in Python canbe broadly classified into 1. Empty Lists 2. Long Lists 3. Nested Lists three types: [ cmaneenan ee ot Bet Ds ee lee nai, tart, [Be ceenerio, 20,3000 39) egress 72a, 20, 30, $0, 50) tu sSetzmt "sen, 450, 20.4, rte aa fea exes 220,220, (2% eh etme of eittorene eee | yee oon. er ets 6 7 0) ies Sierne(01,4°9,16425,36, 49,4 sas. srepe25) as ha ne or de 8 96 36, 25, 36, 4 eh, a2, 99, Is Rae soar rate 2s 221, 4 16, 95, 25, 256, 79.73: rag Oe ts Theses canbe created in Python by ping ot a nga rontot Phan hel rompt>> and dpayin its contents by simply typing the list name, as shown in Fig. 73, wine sin Creating Lis from an Bisting Sequence tn Fython, Ist() method takes sequence types and conversa gven record/tple or string nt alist, We ean create alist from an existing sequence using the built-in fuetion Ist) in th ollowing manner: 1 An empty list created with built-in funtion ist(), as shown n Fig. 7.43} Birremasase oe ie tt htt Osi Wao He Fycen ao.0 tora hrctons, oR | essen) me vine ene mee) oe poe Sherott Scapeige' necelee™ 0 ewsnet 1? for nore’ safari. mn eae ete acing an eae Mat | xp Sie | a Fi Ta renin stg Fncon ® scanned with OKEN Scanner errr rrersceee time nth chapter, we wi focus ony oF and the in successive chapters 72ST ace of values (ens. The elements ordered seaue mati amis colton of values F20or oeven alist. The values that make ist gets, ato be of any type, string, te seein square Brackets [] separated by 3h ts ofa ist are ent ed by co ealdtslenents Een fe emanate scene BY dee. na, Tie allow dupes wale 2 wel THe hich means that Python will not rg se ee inline a tn ne ot Ihe 8 ake change ett ae Heeogencos of mull PES) in ature ‘Spe inter words, We ike a string (sequence of characters) list ls0 sequenced data type. no como pres es) wo sture Bats Hema a note ofthe same type. 7.2.4 DeclaringGreating/ntiazing List dine can be crested by puting commarseparated value/items im square bracts access the tems “The syntax for ereating alist Is: = 1] For example, L={) — #ist Display Construct Contein a set of values/elements constituting the list with the name given as > Lista, a Hapty Uist, 4 Line rare) 5 SigeP=10,1-4,9, 16,2536 48,64,8,200,0, fnoog Uist, a ust Ev aan Sheesh tae of *henmat) V8) Ast eontaniog enon fe at a, tng Oe ‘esl canbe created inFython by pig i ote In font phon Shel pomp >> and plang its contents by simply typing the list name, as shown In Fig. 73. aliens aaa Creating a List from an Existing Sequence fpytion aSs34:40) ase v. i927 DE Inype mete", scoprright, "= for nore inforestion. S35 abses 0 cag ast ie atte ens poo aisedetist() texting on em 26st ear ase | for mee Snort, 1 Mist veh etmets of eteren Hee tt sees 2 sesage ast tle a sate st i ypesof it |n Python, list() method takes sequence types and converts a given record/tple or string into alist. We can create a list from an existing sequence using the bul See ing Sequence using the builtin function list() inthe 1. An empty list created with built-in funetion ist(), as shown In Fig. 7.4). de> Listzaiict (0) (xo) cediee" oF “Vicense( ng et Function ® scanned with OKEN Scanner (ating), a5 shown In Fie 78°" otring) Creating a ist from a 509 : eneu_List_nane> ~ List (sequence For example, : b> ListteList ("Computer") pop List Tee, sor, tmt Bye Fig FAB Cra “Another example fr accepting the DOB (date ofbirth) as mputand converting into ist ung mene ___+a Seago Fig. 7a(e Converting DOB toa Uist using Tat) Function 3, Creating alist through user input using list() method, as shown in Fig, 74(@). ‘You can create a new lst by extracting the elements from the user through the command prompt and using builtin method lst). * rin function can be wsedto diphayanente st, «st function can convert certain types of objects Int lists 8) esgic SSIs oy oi Listen (ae AMEN nde, 2,3 om at ai + 30, 40) ae r slements present i a Mavi 0 20) 30 a, 1.2.2 Aecessing List Elements (ndesing) Se st consists of any collection of tema fomina list an Be acested yang sane roc a8 hs nde. ike sings, any {postive index) or from right to let (negative index), The inde ang ne OM Het ight tothe second last item and so on index value -t refers tothe atitem, ror eample, Consider list containing 10 elements Ustl ~ [10, 20, 30, 40, 50, 60, 70, 80, 50, 100) ‘This Ist in computer memory shall be represented as shown in Fig 7) below. Fig. 75a Postive nd Negite dors no ik Fach clement of the given list can be accessed through their indexes enclosed in square brackets. Fig. 7b Accessing Ut ements trough Indeves Spy ® scanned with OKEN Scanner cys Peasser acter tst wi elements sn Fig. 75(0- ing an Element of he Lis Taticens rade Memory and AES fe pepsin : aa sdement that does not exist inthe list It wil dig access is Indexerr apearsifyou By and 3 the error message as: IndeXELEOE ee a Fig. 71d: Representing inexror son gence. we ing ears wear ring ln wh doesnt pe lent ander Python lg neo 7.2.8 Traversing a List ‘Traversing alist means acessing each element of the lst. This ‘or while looping statement. ‘Traversing can be done inthe following three ways 1. Using in operator inside for loop ‘The elements of list can be accessed individually using for loop: ‘As is evident from the output, in the fist iteration, variable ‘will be assigned the first element, iz, 1, then the second element, 'e, and in this way each letter is. accessed and displayed on the Python Shell upon execution, pained) Each elements displayed on a new line tilall the elements are traversed and displayed. Here, n operator using forloop iterates each element of alist in the sequence. a_e endex ovt of Fange,asshown in Fig 75,q) ingto acess the eighth element (>>>25s¢ (81) from the ig per of 8 elements for which the last index is, ‘can be done by using either fr come selec a Sdn aise: foe sunt using range() Function wei aey dood hs toa ales deed hs ten Chap cs mantoned he sume etc nes ee en ee {individual elements ofa list, using indexes of elements only alonsave ne ee «ives the length ofthe list and specties how iy alongwith len() method, which pase = OP YE, OT aT Jn = aenaise tien fecharacters in a string sor $n range ta): print Qisenis)) counts the total amber of 3 Using while Loop List elements/items in Python can also be Mterated ot accessed using while loop. Firstly len() function is used to determine the length of thelist, then while loop stars from index 0 and is iterated through the list items hy refering to their indexes Unlike fortoop, eis a must to inerease the index by aftr each eration as showin example that follows, no eign ® scanned with OKEN Scanner ingen = 0 tiie fade < rene ‘eine ayiseetintes) Segoe Peerage: ex/0sers/oreetiepoata, | fenitore-er | Sefeeattes Practices |intoration Tech 7.24 Aliasing ve create in Python are also objects we are roe Inython, vals refer to ojos. Thess we create in Pion are also oblects Weare refering to. Since lists are mutable they can be modified If we assign the sto anata ‘both shall refer tothe same object. For example, Let us create alist named subjects containing names of four subjects as string type: >>> subjects= [ ‘English', "Maths", "History'] represented according to thelr index values Sin ‘The elements of subjects list in memory are repr ce the list index always starts with 0, so Hindi is stored at index value 0, English at index 1, Mats atindex 2 and History at index 3, Now we will assign it to create a temporary list of the already created list, subjects, by giving the statement as: >>> temporary = subjects ra hell rs Now we have two lists having the same set of values. In other words, temporary is an alas (alternate) name for subjects list, as assignment with =" operator does not make a copy; Instat, ‘itmakes both these lists referring to the same location, We can modify the contents of these Iss by referring to their individual index values. ‘Suppose we have to modify temporary list by changing the subject ‘Hindi’ to ‘Sanskrit, whichs stored at index 0, by giving the command as: >>> temporary[0} = ‘Sanskrit! >>> print (temporary) USanskrit', "English", ‘Maths! 4 >>> print (subjects) ['Sanskrit", English’, ‘Maths', iistory'] "Bistory") changes made with one alias get reflected in grt diferent names pars sted in th other alae Swe can sy that he yop subject Codes = (‘Sanskrit ‘i +431 UEngtisn, a5 Rie eeeret ears cea eel sctCodes (1) (tenglish", 85) o> print (gubjectCodes(1) (0), sup nglish 85, ect Codes (1) (11) ofthe index value, 7.25 Comparing Lists ‘ompare two lists if they are of compa For example, Consider the following lists, rT, 0a (28,20 feed ae ae [hom tn the given example the second saenent erates to Fe becuse a need pat 41 Isa simple list. Thus, on comparing generates Fe because bat ss are diferent ater Python generates the final result of non-equalty compatisons as elther True/Pase from tom’ Pondlng elements’ comparison Wile comparing wo ls checks element element cenfaton the corresponding elements real It >on othe Nest eement non f "fads the element that dies. e—s aon ® scanned with OKEN Scanner .. conte eve they ave ros 8HOWN Te any Ibsequent elements ae not cms tne 2S Toe (fi2zabtizoa Tee Tnaaaicnasay Fake 42 Foe oe tn the given example, on comparing the fis, second and third APSE, SNS Tre, Comparing the fourth clement 4 which not less than 2. Hence the oat ‘becomes False “Trost for eomparing to ists, Pthoninteraly compares individual ements f yyy, applying ll the comparison rules Fig. 72,, ‘onton Opeatonson tar operations ui aistl = ('Red", ‘Greeny 28 cample: List? = (10, 20, 30) "aus discuss some important Consider the following exampl 184 Concatenation co ner with the help of certair ‘multiple sequ EEE ans x opt mae gunn can be omhing eas tection epee Cates ae owe Span | [For comparison operations, Python ignores the Ise a a lypes of elements and compares values only. pea e see t aeaen sy sii mea In the given example, the second statement (Il == 13) results in False value since the typer esis rosea Tt heal fot both the lists are similar Inthe third statement, the two list are similar and, bees, freatr than (1 > 12) operator results in ale. But when we compare the two Ist, I and, tthich are of integer type and float type, respectively it results in True. Ths is because Pythe Int and float with matching values are considered equal and, hence, the output become ‘True, Therefore, for two lists to be equal, they must have the same number of elemens sat oe hing li 9, 7 Us Conatenton ing ¥ Oper >> Listl = (1, 2, 3, 4) >> List2 = 15, 6, 7, 81 * operator concatenates lists: ‘Example 4: To find at least one common clement between the two inputted lists, [Binaeasy:Ghiewinannoatee ~ 0% see = 105, 70,5,5 Pipe *copyrisns, trettar or "icon pos uistae 12,2,308), o> asean (6.7/8) >>> tise = Listas wise po> print asses) Oy 23, 6 5 6 7, 8 | FESR © Geena Fig. 78h) Operator Concateats ists fog ® scanned with OKEN Scanner an error since CS ot OF ist + 40 shall generate ‘numeric value in ‘ean be performed es ves shown in the give FB 7.810). Python wil generate TypeEs opertor Tip Tater i contention ub + OP concatenate a Uist with string value 1 wil gain gen Sina nF, 78). e U9 nen en sed wii QUES DU he opgang _genberslP testing ian Operation cred ox ea Chena fam sa member ofthat Sequence or at Ors whether parte ames | rac belong tte sequence of as : uence. Hence we say that he left-hand oat BE io | ‘sa member ote sequence of ers ypeetics ty conatenta ist aot “ste") to itst | = Tae Reng ee 7.8.2 Repetition Replication Mull (asterisk Le, *) operator replicates a st fora specified numberof times and ees tn Fig, 7.9(a, list2is multiplied by 2 and string ‘Python, represented asa list, is multiplied by ‘Thus, the lists printed two times and Python gets printed three times [Fig. 7.9(a)]. However, ve ‘cannot multiply one list with another, as shown in Fig. 7.90). a | font pe Tiepeat ition operation sist? = (10,2030) peineaistetay tytn in operator checks wha gad tlement appears in the list; iia otherwise it returns False [Fg 7.106) eotszyenen'}*9 ems aarp aga /Roeal segs! || Jpeist tn Using ® scanned with OKEN Scanner re tv is not in The operator not in returns True If the clement does fin is not yerator not in ‘does no. Ti reverse in {nthe list, othervise it returns Fats (Fig. 7-10(C)- a jlarly. in Python, an index ‘and ni*elementis nay list Index of ge th poston fet gene of cement in alist. enables el LN pon, ithe lists, second element nt Identifies next tothe er to et 0 the last eee {£4 ofthe een are Index -1 dents tet nn ne 7a3g0) rratrnotinin Lists Fig, 7.0(¢: Implementing Membership OP {in Operator used with for Loop 0 display the elements of a lis In this method, membership operator in can be used to display * through jy loop (Fig. 7.10(¢)). For example, ‘To display the names of students who are members of class XI. 738 slicing Indexing and slicing are two inter-rg Letus first understand what slicing is Fig. 7.10 7.3.4 Indexing Fig. 7-2Scing Operation Sicng isan operation in which we can sic a pati ticular range from a sequence. Inthe context crrrvensa mazine You want to aces only the as sung ith te DRceatj once Tedeen a @ Sequence, So, the range tobe taken sallbe from index Indes 4 whee doce ‘Stabe excluded. Now we will se this operation on ists {Bkstce ae the sub-parts extracted frm ist. st scescan be erated using Index is nothing but an integer value for each item present in the sequence. So, you have 0 Index, 1 index, 2 index, 3" index and so on, depending upon the sequence. In Python, indexing starts from 0 like other programming languages. As shown in the example of sequence of cars in Fig. 7.11(2), we have 8 items in this particular sequence and the indet ‘ange is from 0 to 7. Thus, ists in Python can have/store different types of elements stored int particular sequence such as integer, strings, ete ‘used to retrieve a subset of valu SRS ES ES EAE | | Ast istart:stop:step) tere, start is the beginning point, stop is the end polnt (which isnot incuded) and step is ea |p memantine ter a [rues [ied] [tea] [rte faexs| [index] ae ono) compte cee to e—s ® scanned with OKEN Scanner se an example let us conser aTs/sequenee "To take an exam shall generate the folowing this sequence Sop formed 08 ons perl ‘The varios sling oP te me) xt126:2) (10's "Pl aa Eee ea es) tes] (rete '0tn 8s tatten | Em ere | xI-3) eae ee epeyinty Ee eae me ea " ih he following values and results afte icing opera ghaurya", 900, 897.60] ‘Let us consider another ist, st Listt = (200, $0.75, "Radhika", seat o “iene fo nate nto Kegiee parsers a ea at i.723: List Scng $$$ rte screen rv sated as boundary and the rest wil singly coat toundary, Incase the start and stop limits lie outside liebetween the spectied range /boundary CS ——— issn is done by ea ink() statements, we have gee elements ang ee ese “chy read also be done using a variable yy : Pe etter « 35 be Higa {tos "aby extracted from lice is alist itself, Le, we can i corm at soe the vara The hus when we ty to modify the lt ees a dhe sie, is alist nits fons oni just like we perform on ists, “er slee Its sucesily implemented sre ou og OU of range, Sie ra ee. Slice range (start and stop arguments) le elements which le between the the boundary, Pt hon sl oturs the element Without rising =e any error. GS BR Be manera — be lstios 8, 28, $0.20, 22, 4) [2 sey oy a pea [e, 995 29, on b> sistatsao) 2h ae at) per aists (ciao) 20, 2 ‘Sa o> istuteis [oa op Lindt fs out of tous >> aiserto:z0y snot aunts ace oat of tends ae ‘nthe last statement, both the limits are out for but returns an em 10020, of bounds. However, Python sil doesnot give any pty list a5 no element of lit possesses the index tha fs n the range start Index vale sing, then wil tr frm Oy deft ad stop wale print lend. Stop inde, igen wlstop atindexsop-1 Le, tp sexe, TA NESTED LisTs ettalistappears as an element of anther Is, A nested liste, alstcan have one of > ste) ‘relists as its elements. ae "inten S23 Hilt lesa of Le is eae! s ase e—a ® scanned with OKEN Scanner yod 2: We can use the list consty jie = Mat (oldhist) yecify two indexes |>>> list; Pre the ements tne tol eb tise and the [2 TT ed oe ee ving the ith element 25 4s passeg ‘The piven outputs generated a8 7 because 18 cas 1ispassed 2821 AFEUMENt inthe yes yout any ar % Tn wares este seme 57 se ng thou any arguments wi egg t—— oS ‘3: We can use coy empty list, ist ont pod 3 P90 finion as ato . west = [Link]() haace! Pe? BASE as, emago's Se 6 7, (Uaack's foams TT 355 finches} 716 BUILT-IN FUNCTIONS (MANIPULATING LISTS) won offers several built-in functions that anal Pris sich a addng new clement Me en et eather han ren ing the elements ina list, te. These fun perform varus operations on lists, 3s shown in Pip. 714 ac 7.5 COPYING LISTS “The simplest way to make a copy ofthe given lists to assign i to another list, poe Hise append 0) b> asset fay 23 201 iss Lise? fa 23 20) ot appends) (Cont + =- (rt > tat nay &as- a G2, 3 et tndn(oted ‘The statement list]? = lst does not crete anew list Rather, t ust makes list and list2 refer encase) the same list objec. Here, list2 actually becomes an alias of lst. Therefore, any changes made to a, ee either af them wl be efecedinthe ote st ae So ee ee =a sod enahng etna oped tes bain clon i) ad he ad ed =. _. copy() function of Python library. Cc} aingiat), Me cn kr rapa and aint eg EE lor ene ee nowList = olList(:) 18. append() ‘pend() method adds a single item to the end of the ist. It doesn’t create a new list; b ‘ales the original ist. single element can also be lis. Us syntax sy Uist. append(item) bbe numbers, string, another Ist detonary. ee _o3. ‘Computer Science wits PY" rs . ® scanned with OKEN Scanner Implementation-2 ».. end ofthe ist. program w ota per ae ple 5: Write a program f0 “Avjorcan aso be added to an existing Hist. Fr example i. i, co tn, 0) ferment ta list ‘Beample 6: Write a program to add an element re ee ne mate Le 1.62 extend) tend) method adds one ist the end of nether i In added at the end of an already created list. Peake Ot tseymtaxis seeps [7 The list which wit be added to tis, stl extend (1ist2) Petal implemen pees ee ist is the primary ist which wil be extended, ‘Write a program to find the se Example 7: Write a program to add alist tthe end of another Ist, TeeTants /sera/peee/aposta/tocs/ Pose lint! Yae mater of eleneats in 2 2ist | Pannen sess errs 809 | IS 3) 6, 3, a t eo te pe man ies second Largest elenort fs the i— 64 ® scanned with OKEN Scanner tend the exiting Uist je ith fpsegeen to teed 3 Te Ergun clenat ond 9: write a code 1 o> L1=1100, 200, 300/400 3o> 12=[20,20,30)—* oo eee cems of Iist2 added to list? >o> print (in) 1100, 200, 300, 400, 10 20, 30) ‘insert() ef at (ip (7 seanetenajec ata seid inde. TS fncon a me a a eta 9) used to inset an element aes eeaaere esse ore Dae {insert function ean be ‘wo arguments the index where Its syntax Is ‘tet name. insert (index sunbery valu) “bjs toe inserted ad the Rem/slement ae, ita se ay sovete y Here, 1ist_name is the name of thelist ‘ndex_numbes isthe index where the ‘valve Is the new value tobe inserted inthe ist, new values to be inserted. ‘Example 9: To insert an element to the list Pai fn = - chon, reverse() function reverses the on Barren nce eee of ems a other vt "Yale's place’ of an tem tht already exists in isin . ae nese: cise pee ii = (0,20, 30, «07 >> Hamendt ts, 60)) 12,20, 30, 40, (80, 6031 o> sista =” (020,30, 40,30) o> Listi. insert 2,23) SS hase 20, 26, 25, 30, 40, 50), >> ists -thserti0,8) B33 ase 5. 10,20, 25, 30, 40, $0) Practical Implementation-3 ‘Write a program to read alist of elements, Input an element from the user that has to be insetel inthelist Als, input the poskion at which isto be inserted, Apply a built-in funtion tse the element atthe desired postion Inthe st Python, {ndex() function returns the index ofthe first matched item fom the list. e returns currence of an item for which the index postion isto be searched in the ist If the e—s ® scanned with OKEN Scanner Be Pen st. indext pelne teeter 2)) 7.8.6 lent) an Jen) function returns the length ofthe list ke, the number of elements in alist. Its syntax is: len (List_name) opvlgnt, teraitet of “License 7.6.7 sort() and sorted) sort() function sorts the items of the lst by default in ascending/increasing order. Tas | modification is done ‘in pace, Le, it does not create a new list. Its syntax is: [Link]() Example 14: Write a code to sort the list. far Ger, 9, 100, ‘Computer Since ir ii dears lm Fe es io fet de ing is done gy cy ten he bast of thelr as Yate nual, ie Went elements Cl values Python stats by 8085 onto the next element ‘te not considered (even if ey have large values), resorts te string Ina lexicographic manne, irwewantt 07 thelist in decreasing rey, o> List sort (reverseet>ue) "WE DEE to write the following rans 80, Sarena eersoct reverse = 5), ee eben peg e839 ;, = isseoae, "Reem", ', eek, sorted()}—This function also sorts the items of the ist Its syntax is: sorted (list, reverse = true/false) >>> sth = (4,2, 1,9,3,4,6,8,51 >> sorted(List) 11,2, 3,4,4,5,6,8,9) >>> sorted (List, revers 19,8,6,5,4,4,3,2,11 >> sorted(listl, reversesFalse} 11,2,3,4,4,5,6,8, 9] Uke sor) function, rue) N >Fted() function works n the same way as sort( function, the only diference being that {returns a new list rather than modifying the list passed as a parameter. "4.8 clear() ‘learQ) method removes all the items from als, This method doesnot take any parameters.) ‘ly empties the given list. It doesnot return any value "syntax is: [Link]() ie Pten e—a ® scanned with OKEN Scanner ee am ree mon ee isa) aw ste 3 ae ate 7.6.10 max() Returns the element with the maximum value from the is. Its syntax is: max (List) Note: To use max() function, all the values In the lst must be ofthe same type. Consider the given examples: 1. >>> List3=[10,20, 30, 40) >>> max (1ist3) 40 2. >> Listas['at, tat, >>> max (List4) ‘Here, it will return the alphabet with the maximum ASCII value. "Bt er] . — tar e pep max (lists) harat oy tehelly" Herel UE he sing yy ih stars Dg pe? Lists art wt "ashwin', ha arate ees iis, oe ng the behest ASCH sale ree preee") if ere a6 00 oF mee stingy teed et a ee g : rice thn the second 16 mint) pats the ele emma ay Its syntax: min (2st) Om the i Note: To use min) function al the values ‘consider the given examples 4, >9> List3*[10, 20, 30, 40) >>> min (Lists) 10 2. >>> Lista=['at, tar, >>> min (List) ro thelstmest eo the same type Here, it will return the alphabet withthe minim 3, >>> ListS=[tashwin >>> min (1ists) ‘ashuin! Here, it will return the string wt A. >>> dst 5<[ asain’, 5 >>> min(lists) ‘ashwin! ltherearetwo or more sting comparedand soon, 7.7 UPDATING LIST {istsare mutable; you can assigna new valuetoan existingvale. Wecanuse assignment opera ‘change an item or a range of items. Yssymtax um ASI valu, shelly! /tharat',+ hich stat with the characte having the smallest ASCH value. warat, “shelly*, urpreet] is which tar with thesame charset then the second characters 1st [index! yen 2—B- ® scanned with OKEN Scanner ‘Mi Example 19: Write 2 code to update a list. Sample 20, Weean alo creates net om an exiting a wigs a8 yeacn 3.6.8 os. e-sirsbeoonao, Rar BP BOE, TO 6) (HCE 1506 32 Bit (aneel)} on Wa? pe, ccogclti, Pecaitat or views)" for aor Re righ aL pee ees pinky erageyllon 7.8 SEARCHING LIST Lists can be easly searched for values using index() method which expects a value thats tobe searched, The output i the index at which the value fs kept. Its syntax is: 1List_name. index (element) Example 22: To search an element from alist. >>> Listi={100, 200, 50, 400, $00, *Ranan', 100, 'Ashwin'] >>> List. index (400) 3 Explanation: Here, we are searching list forthe value 400. The answer is 3 as the element 400 is preset t the index value 3. Jf the value we are searching ina list isnot found, then an error is displayed. rer since nnn nl ” om ate, > List index (209) 0, trae P + 200) sastytns) ° qoismethod On eu gene, present at Be OF 20d 6° Inder Soh ig 242 To ius “IS the Onder "ENED ere, the lement 100 sample 24 Tins nd men le 100i yp? List" [200, 200, 50, ¢op gu, pp List index (709) "20, ein fraceback (HO8E recent tt tae, File " $00 in Lista +100) "Ashwin rue planation: from te gen example, Is evident hat Tue was tun Ise 7.9 DELETION OPERATION Python provides operators for deleting ‘There are many methods for deletion: eds the value 500 was present in e/Femoving an item from lis, 1 Iehe inde is known, you can use pop( fonction or del statement 2 Mthe elements known but, not the index, remove( can be weed. 3 Toremove more than one element, del with ist slice canbe ured 1 pont) {eremoves the element from the 5 Its syntax is: [Link] (index) specified index and also returns the removed element, Example 26: To remove an element from the lis. >> 11 = I, 2, 5, 4, 10, 10, 90, 80, 50] >> [Link](2) "here the elenent deleted wilt be returned Pg #2 gets deleted >> print Gay {4 8, 4, 70, 10, 90, 80, 501 e—a- ® scanned with OKEN Scanner ia bon pont funtion, ton the at lement OM th Be index value is provide et sooi.ror0) so (can be used wt ror eyo, 200, 380, 5001 pp uipor( soo dex value also. seenes ie toomasis fom the Ist Dut does not TEU the de, >>> z1={100, 200, 300, 400, $00) >>> del 11131 >>> print (Li) {200, 200, 300, 500) Note: If an out of range index is provide >>> L1={100,200, 300, 400, 500) >>> det L115] ‘Traceback (nest recent cal last) File "epyshelW31>", Hine 1, in el 1115) indexer: 4 with del and pop0s the code Wil resin ating st assignnent index out of range det can be wsed with negative index value als. b>» Lie (200, 200, 300, 40, 500) >>> del uaf-21 >>> print (hd) (100, 200, 300, 500) del with tcing Its syntax dol List (start_indexend_index) Consider the following example: >>> L1=[20,20,30, 40, 50] >>> del 12224] >>> print (Gl) 120, 20, 50) ‘The given del statement shall remove the 2and 3 elements from the lst. As we know slice slats al the elements upto the 4 index, so the 4* element will remain Inte! 2 e—_—_ compat Se 5, remove() See rerove)fnction sed when ofthat element. = 100W the element ies symtax is: thats tobe deleted but not the index Lst.-xenove (element) pri = (1, 2, 5, 4, 79, p> Li. remove (90) ‘The given statement wil remove the value p> print (2) M690 trom the is, {1 21 51 4 70, 10, 80, 50) prstical Implementations aE TS IS fiset = 1n,-2,28- frei = venthistay ho jndue $< rents eur fied v2 wo, enn = ten print (ist after deletion + tis) REST: €1 Perret ngpatrica BAGH attor celetion « 12, e446, 4) Practical Implementation-5 Write program to read alist of element elements, fe, all elements occurring first occurrence should be displayed ts. Modify this st so that td ‘multiple times in thelist sho in the inal is. foes not contaln any duplicate ul be deleted and only their tvoaity this Lists that it ee ast coctain feny Siplieste lesrat astwvak dapat reser 9 ist ioe & in sargetentst: tory ine de tetlommet > 1 tent apiece scenes es i { 1,2145,2033,65,01 23,65, 4 ia ten e—a- ® scanned with OKEN Scanner sore List Methods In a Nutshell n asten 1 the specified index. When an Item is : tem it he i 3 inser [SRSEEE Unde, seen) ss ceanedin se to accommodste the Ne. The ken hy ed nex ado te sbsequet Hers ae shine gt sdf tet No exception wil cc You spe) fy et eae ' peel 2 5906 } prstlon towards the ta you spec anindox beyond the end ofthe Is, the reed athe end of tet. you ue a egal Index tha spec |. +a tee be seted the began of the et, sort) orth ke nthe st 0 they pp 0 cong Oe (om the ayy Saetothehighestvobe), i fist ctrence oftem rom the it. me reverse() ‘Reverses the order ofthe ems inthe list. Practical Implementation-6 list, Listi=[10, 20, 30, 40, 10, 50, 10) iset= (10,20, 30, 40,10, 80,10) fnumeeval (Loput (renter 4 numbes:")) eount=0 for tin asta: Sonam ds ‘countecounte einen, "is present", count, “nunber of tines") Jveeeonwneeeennweees RESTART: Ci/python36/proq_lsti4 a. enter a muster 30 30 4s present 1 amber of tines 10 is present 2 number of times 0 presen 3 nober of tines nce ofthe fst elerent whose ole I 4Ua 0 Rem, URE etary ‘Write a Python seript to Input a number and count the occurrences ofthat number ina gig, yctical Imprementation-7 Se a ee for Uineat Searce pasty Ton tdsed) nn USE ete, ee = tn SBDULEtes tt met cangetOrleageayss © SEDO oa yy = f, eronent = Distt eine element, fois a Ersar Ide | hed for 299 | q ” 200 200 a 8 se : Present [athe toes tan srenp © (Mon, 45, "Tue', 43, raegs sun", 38] Wed 42, Hho, 40, opie sng the ven Ist, write a program to creat 38, tsat', 40, pays = ['Mon', ‘Tue", "ma", for tis rtagecny ieee = os "ays. tppend ett) cine corigeent Tet ge essere cays 7 Practical Implementation-9 Write a menue riven program to perform various list operations: (Append " ©) insert (9 Append a tist to another list © Modify element P Pott eitng element rom the ge postion ete existing clement with the given value Sn iton eo —B- ® scanned with OKEN Scanner sos Sir We st | Bclalitta ee on Tages eo Ree siesnsinctiaet amar mv elements “Db see ponciee ot tutment tobe anata: 3 low ier tir 22,5) Shree uae to ¢ ere an lene a desta poitce S: dees tle to rn ie Staats eniseing fio ena erg RS oo pee Suet sulci sheet oy 182 US Ge ora, “notes gor 740 SORTING a8 SMEs agg Stree dt npr el ‘tre ine Serine ies i the datas stored ina sor co sr Ther are vero ets a Seche a g femets Song eae deere Hee dan 4, Bubble Sort nique . thm specifies the way. tized to avery high seo data in more reaatie 0 the Tt in ascending of 4, Insertion Sort 140-1 Bubble Sort sone ofthe simp ple sort le eu raat len eg hm ang a inch gorithm. 1. START 2 Read the array elements and store i g,store the length inthe variable n, {for ie0 0 9-1, repeat steps 5 ana 6 5: Foro 0-0-1, repeat step 4, [Link]] > al), then swap elements, 1. Display the sorted ts. ND ravers the whole ements onthe wh ee TN elit is sored, insta) nd following the sa Second element is greater than the third element Wah the greatest ofthe first 3 elements onthe thind psi last element, the greatest element willend upon the lac the first step in bubble sore. 2 Aer the first step Position ofthe list. there are n elements to fet the required result, For performance o compared si ‘salready p me lgi they are swapped ithe these two steps, tis ensured that nhs process is repeated tl the postion inthe st. This completes ‘ets completed the largest element in array wil get placed inthe last. be sorted then the gen process shoul be repeated n-t times to )ptmization, in the second step, the last and second last elements are not ince this comparison was already done inthe previous step and the lst element resent in its correct position Similars in the third step the second last and thd ast ements re not compared an so a Men e—s- ® scanned with OKEN Scanner os ros se this with te help of an ex ‘Sorting in ascending order using bubble 0° Suppose it (42, 29,7413, 65,58] First pass h99. 74.10, 65,50] > 9.42, 7411.65 58D 4 —> (29,42, 74,18, 65. 59D 29, 42,11, 74, 65.580) wil swap since 29 < 42 no swapping as 42 < 74 (29,42, 74, 11,65, 58 pe oy (29,42, 74,21, 65,58 29, 42,11, 7% 85.581 29,42, 11,65, 74,38) — (28,42, 11,65, 58.79 ‘will swap since 11.<74 29.42, 11,65,74,50)} will swap since 65 < 74 rewill swap since 58 <74 Second pass [29, 42,11, 65, $8, 74] > [29, 42,11, 65, 58,741) 29,11, 42, 65,58, 74) wil swap since 11 < 42 no swapping as 29 < 42 (29, 42,21, 65,58, 74] (29,11, 42,65, 58, 74] —> [29,11 42, 65,58, 74} no swapping as 65 > 42 2s, 11,42,66,58, 74] — [29,11 42,58, 65,74) il swap since 58 < 65 Third pass (2b, 42, 58,65, 76) —» 11, 29,42, 50, 65,74) wll swap since 29 > 11 (11,2942, 58,65, 74] —> (01, 29,42, 58, 65,74])_ no swapplng as 29 < 42 (11 28,42,58, 65,74] —» [1, 29,42, 58, 65,74]} no swapping as 42 < 58 a" Fourth pass 111,29, 42,58, 65,74] — (11,29, 42,58, 68,74]} no swapping as 28>11 [11,2 42, 58,65, 74] —» [11, 29, 42, 58, 65, 74]) no swapping as 42529 the total numberof ete OS say ng el be 5 psses trough ee Souter 1D be ene cited n- th pass pl con times Le, 5 times. v Bach pass places the next a POPE dio reach pass OF OB T00p iteration, lems gest a et ite ee elements 8 they are ales einitecetltems and swaps ready paced at yan Ps those that are notin cornea, Plaee and there ade rag haa terels once camper practical Implementation-10 ‘Wate an interactive program to create a arder using bubble sort method integer ist of “SB et oF integers an sorte list in ascending fasinetierat Eowresita Some. Mita. Law ¢—2 ® scanned with OKEN Scanner Se ga TT | amen Troan con | Ge Fe ce mnt at | echo ents <0 Y ic Ma ae met rm cee | are being inputted by the user inters In the given program, the elements of the ist ae beng inputted by the Progra sce asys (y or ¥)- The inputted elements ae appended nt fe ee soit angbbblesor Buble SOT Meted cna the ajece element of st staring wth he ist 2) and second (12) ements, gg ty swapping (22 being swapped with 12) ifthey are out of order. Just Ike the frst and seco Clmerte he thint and second elements are compared and swapped. Ths process continues intl the end ofthe lst and the output so obtained isthe sorted isin ascending order, 7.40.2 Insertion Sort and you have to sort these In ascend Suppose you have report cars of 10 students and you have to sort oid according to rol umber. You wil have to go through each report card from the start rte ay dnd find ts right poston by comparing fs rll munber withthe roll number on every oes teport card Once you find te right poston, you wl insert the report card there. Simla Inore new report cards are provided to you, you can easily repeat the same process en ine ‘he new report cards and also ge the report cards sorte. This is exactly how insertion sort works. It starts from index 1 (not 0) and each inde tating ftom inex is ike anew report cad that you have to place a the proper position nthe sora subvarayon the left Algorithm for Insertion Sort Step 1: START ‘Step 2: Enter the elements in list , store the length of ist in N. Step 3: For ON, repeat steps 4 to 8; otherwise, step 8 Step 4: [Link]() ‘Step 5: While (A[J-1]>Afj] and j>0), repeat steps 6 to 7; otherwise step 3, Step 6: A(j-1], AU] =AGj], A-1] Step 7:)5}-1 Step 8: Print the lis. Step 9: END $$ rrr snc vn rer iv pee ee vp oF an example, insertion, Moon A220 ore ig 1 ist (7049.31.565 6,65 onside ss SP ailinentiliy ce to second pass Sedelements Ussored elements [p06 65,8168) 9,21,706.65, 0, 9 +66) tewil swap since 70> 31 1.68) ‘il further swap since 49> 34, ‘Third pass, Sore elements Unsorted elements oy [31,49, 70,6) 65, 81, 68] —+ (31, 49, 6, 70,65, 1, ‘68]} it will swap since 70 > 6 12149, 70, 65, 81, 68] —» (31, 6,49, 70,6561, 60) itll swap since 49-6 49,70, 65, 81, 68] —> [6,31, 49,70, 65,61, 681) it will swap since 31> 6 AB eet of he ry i, cpt we et lore ie. 70 fs. tn ih © dtd ayaa ein ete ea Fourth pass Ser lements Unsorted elements oat 1.3149, 70,63) 61,68} —» [6 3149, 65,70,81,6]) ew sap since 70> 65, ofthe aay, amped with te ears at rele, Ott Shee > 6 kwhmap ah 7a ret ake pce becase 65 any ced os oe peso, e—e ® scanned with OKEN Scanner nsedelemen sng wink pace since 79 « % 3 Joo, 3149, 65,70 81,66 me PPE 70 ‘lst a mutable sequence of values which canbe o any type and. are den by an integer. teen ee 3AM created by lacing a th ans ers) nse baat pte yon Peat ive 0 na nosso) > lis can mbave another st a ante The cle needs. > Tepe st means accesng each seme of Ts one ee bg he for wh pe Bateman 3 Rang alows you to obtain a beet fens ome $e anton returns the ttl number of ements the > San combines to orm new petri emanation it is “nebo checks whether hen tev, itretuns ae ‘8 compare two lis by ung comparison perso > 26 8 rertcantandina et. rein Tei helmet appease compas vt BUargey ® scanned with OKEN Scanner ee eeaemant a sing it sce. W) REKL= (2, 2, 3) gy late aay Foxx ntsc i «gn ns at feeaahye ea ws Sena mato asa sing tem 3 SS «a whale he out te PFI ise yy rine tid ner ed Ae Ome tine Cr area ae > Srwcton ens set oe ans eae a print entoes higg ye Hes know the element t Je can access each eley > revel function s sed when we inden), cle), count insert reverse Sor), sory ow MEN Faso tae 5 Thre are vrata mei aor dg oe. Sonne EAH Hina (i) fortoo i) wane 03 ty Was ements ofthelstinascendngo reg st will be the out ae Teen > Soringistoarnetie (Wea BMF the coving eho t,t nd ata ina parte ter new_list = "1234" 1m code? (None of hese Greene) T nS it ay H 7 woe UL (9 Suppose 1881 = (1, 3, 21, whatiga,_ tM) Manet these 1 oes ee eines gs 8,24, 3, Woe ein see of vn 8p, innate wierd tina — IZ, (0 Te postion tc ee awe an deat presen the Ho, esac nie «-21) | " : (9 fava cn eae : Aisey teste al (8) remove(} function removes the -..-» ~ occurrence of an element from thelist, {h) Which of the following will create a true me ry nn Statement works similar to pop) function. () Want fempvotks tt? Be Semen eats Ce cay es 0 a en pete ce, aS eras tm es naa oy alana eine oe 237) es ect : ean Ret Tone eprter a onetane a, . ()Insotman pine { {22,21 gett et mn Big 2. State whether the following statements are True or False. G) What will be the output of the given Python code? ae Msti=(5, 3, 9, 0) print @istrt: + 11) @ 10,9,3,5) Gi cor w W iise=ta, 4, 3, 9, 0, 2, 3, 5, 6 utputas (6,1, 0, 2, 617 print (List (7:242)) w (i) prine (Mést(0:9:21) (i (a) Youcan change the elements of. (0) Alt cannot have another list its element. (6) Cutout of at sing al (G) Theindexof the ast element in alten, where nis the number of elements. {e) Ustisa sequence datatype. (0) Mechanism of indexing es n ists and tings. (a) Wecan concatenate only two lists at a particu instance. (th) Concatnaing ast with a integer element shal add the element tothe is. () prine (1421) and print (11+2) shall generate te same output. () length) method returns the length of i. (8) sort function sorts the element ofthe given fi in lace. (0 Unie sort) sorted) method creates 2 new it, 3. Mutiple Chole Questions (MCOs): {9} Datatype sts an ordered sequence whichis. vv nature, 19 atte (i) tmmatabie (a) Bot ana (iv) None of these (5, 3, 8 07 bi th flowing statements wil generat the istletan) 0: #21) us ESS Lvinatis aust? Alistisa mutable Liss ar inden by amneger- leans ‘mutable sequence of values whch can be of nye. Us list are enclosed in square brackets [] and ate eprated by corms, sts alow dete values 3+ Wel. The elements ofa ist can be accessed by isin. $$$ arias sore wn tort et oe.) ® scanned with OKEN Scanner

You might also like