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

List Manipulations

The document provides an overview of Python lists, explaining their mutable nature, how to create and access them, and various operations such as slicing, concatenation, and replication. It also covers the use of the eval() function to evaluate expressions and the importance of indexing in accessing list elements. Additionally, it discusses list manipulation techniques including adding, updating, and deleting elements.

Uploaded by

asthagour014
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 views30 pages

List Manipulations

The document provides an overview of Python lists, explaining their mutable nature, how to create and access them, and various operations such as slicing, concatenation, and replication. It also covers the use of the eval() function to evaluate expressions and the importance of indexing in accessing list elements. Additionally, it discusses list manipulation techniques including adding, updating, and deleting elements.

Uploaded by

asthagour014
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/ 30
List Manipulation Bodicion The Python lists are container Istof values of any ee Ur ‘in place ; Python ‘calaoE ke changes to an elemer INFORMATICS TICS PRAch Tees 7.2 Creating and Accessing Lists A list is a standard data type of Python that can store a sequence of values belong type. The Lists are depicted through square brackets, eg, following are some lists in py List with no member, empty list thoy, # List of integers # list of numbers (integers and floating point) # list of characters [a, 1,'b, 3.5, zero] _‘# List of mixed value types Lone’, "Two!, Three’) # list of strings Before we proceed and discuss how to create lists, one thing, that must be clear is that Lists are mutable (i.e, modifiable) ie, you can change elements of alist in place. In other words, the memory address of a list will not change even after you change its values. List is one of the two mutable types of Python — Lists and Dictionaries are mutable types ; all other data types of Python are immutable. .1 Creating Lists — Z a list, put a number of expressions in s ad end of the list, and separate ig MANIPULATION oy neste lists can have an element in it, which itself isa list. Such a list is = [3,4 (5, 6], 7] risa nested list with four elements : 3, 4 [5, 6] and 7, me Fangth of L1 is 4 as it counts (5, 6] a8 one elena! oe lement, iiss from Existing Sequences Rs tan algo use the built-in list type given blow = esist() object to create lists from sequences ; can be any kind of sequence object includin, strings, tuples, 3 the individual elements of the list from the individual element: you pss in another list, the list function makes a copy, Consider following examples : >») 1 list(‘helle) ol on 12s list(t) 12 Bier 7-)| MLS) ’ x ; uate and return the result of an expression gj ‘The eval( ) function of Python can be used to evalu vena sin For example : eval("5+8') will give you result as 13 Similarly, following code fragment y=eval("3*10") print(y) will print value as 30 Since eval( ) can interpret an expression given as string, you can use it with input( ) too = vari = eval (input (“Enter Value: ")) print(vari, type(var1)) Executing this code will result as : Enter value: 15 + 3 18 ‘See, the eval( ) has not only interpreted the string “15+3” as 18 but also stored the result as int value. Thus . with eval( ), if you enter an integer or float value , it will interpret the values as the intended ‘types: i vari = eval (input(“Enter Value: *)) “print (vara, type(vara)) Enter Value: 89.9 89.9 Enter value: 75 75 ‘You can use eval( ) to enter a list or tuple also, Use [ ] to enter lists’ and () to enter tuple values Es Enter Value: [1, 2, 3] Enter value: (2, 4, 6, 8) I (1, 2, 3] @, 4, 6, 8) ae a Hovrevs ust of eal) ay esd to anforeseen peablems, and this, use af ealtpi always A500 . 7.2.2 Accessing Lists | MANIPULATION lot with Strings ilo! a ist pats! are sequences just like strings that You hi 8V8 teed in press piindvidl le™eNs just like tinge a Recall ig P*evious chapter, They also indeg the . exing in strings. In the same manner, list-e igure 4.1 of chapter 4 that talks about So jj. and backward indexing ag re also inde ada xed, ie, fi indexi 2, =3, [See Fig 71a) te, forward indexing as ements a 364 | tett6) = = atte (4) List Elements’ two way indexing i Lists are stored in memo that because some of ty others, they store a instead of single chara Each of the individu stored somewhe —t> ‘g000" 3 pm 4.59 i > Tne [2 al items of the lst are re else in memory (b) How lists are internally organized Figure 7.1 Thus, you can access the list elements you the element at ith index of the li b-1and so on. just like you access a string’s elements eg, Listlil will give st ; List{arb] will give you elements between indexes a to Futin another words, Lists are similar to strings in following ways : © Length Function len(L) returns the number of items (count) in the list L. © Indexing and slicing | L{i] returns the item at index i (the first item has index 0), and amie eae Li:j] returns a new list, containing the objects at indexes between i and j (excluding index j), eo Membership operators Both ‘in’ and ‘not in’ operators work on Bee pes ‘ That is, in tells if an element is present in the work for other sequences, ee: in does the opposite. : ® Concatenation and replication operators + and ther, {Re @perator adds one lst othe end of another, The talking about these two operations in a later ‘We shall * operator repeats a list. ae pie oeetiene: INFORMATI 0 Ics ee Accessing Individual Elements ; indivi f a list are accesse: tioned, the individual elements o! Cee Grogh their indexes. Consider following examples : NoTe sang White accessi ; =[% ‘o', “ut ing list >>> vowels = ['3',"e ] youl pals: Ind fee >>> vowels [0] Python adds the length ‘dey, 5 list to the index to get en, ‘a forward index. That sett peace ed S-element list ty usp (4 u internally computed ay! >>> vowels[-1] L[-5+6]=L 11), and og - en, >>> vowels[-5] Like strings, if you give index outside the legal indices (0 to length ~ 1 or — length, — length 41, uptill -1) while accessing individual elements, Python will raise Index Error (see below)” >>>vowels=['a','e', i, U] >>> vowels[5] <5 is not legal index for vowels list, thus cannot be used 10 acces individual element Traceback (most recent call last): File “", line, in Joes] Se 7 i <7 ETO 2 The for loop makes it easy to traverse or loop over the items in a list, as per following syntax : for in : process each item here For example, following loop shows each iter L=[P,'¥, "th, ‘0 ‘n'] forainl: print (a) m of a list L in separate lines : The above loop will produce result as : How it works The loop variable a in above loop will be assigned the List elements, one at a time. So, Joop-variable @ will be assigned ‘P’ in first iteration and hence ‘P will be printed ; in second iteration, will get element ‘y’ and “y’ will be printed; and so on. If you only need to use the indexes of elements to access them, you can use functions range() and len() as per following syntax : for index in range(len(L)): process List[ index] here Consider program 7.1 that traverses through a list using above format and prints each item of 2 list L in separate lines along with its index. Program to print elements of a list [ ‘q’, ‘w’, ‘e’, ‘r’, ‘t’, ‘y’ ] in separate lines along with element's both indexes (positive and negative). L=['q,W,'e,'r,'t, ¥] length = len(L) for a in range(length) : pr indexes", a, "and", (a - length), "element :", L[a]) al Consider following examples : spp Lay t2= Es 2 31 2,3] yo = [Ls [2 31) >>> LL == L2 True >> LL sek False rators >, 6 221 the corresponding elements of two lists Must by 4 For comparison ope! will give error. comparable types» ° Consider the followin; therwise Python g considering the above two lists : pop Lac 2 For first comparison, Python did not gi A orate ee ee For second comparison, as the values are not of False ‘comparable types, Python raised error >>> Lc L3 Traceback (most recent call last): File “cipython-input-180-84FdF598C3#1>", line 1, in u>>arb False >>>d>a a fotice for comparison purposes, False Python ignored the types of elements >>>desa ‘and compared values onty Tata >>>ace True Foe nwo lists t0 be equal, they must have same number of elements and matching values (recall int and float with matching values are considered equal) sere is also a cmp( ) function that can be used for sequences’ comparisons but we are not covering it here. 43 list Operations pet Spee ‘The most common operations that you perform with lists include joining lists, replicating lists and slicing lists. In this section, we are going to talk about the same. TA) Joining Lists honing two lists is very easy just like you perform addition, literally ;-) . The concatenation operator +, when used with two lists, joins two lists. Consider the example given below : >» Ist1 + 1st2 aes ‘The + operator concatenates (wo lists (1,3, 5, 6, 7, 8] ‘and creates a new list As you can see that the resultant list has firstly elements of first list Ist1 and followed by re lists to form a new list, e.g., lements of second list Ist2. You can also join two or mo! >> Ist = [10, 12, 14] >> Ist2 = [20, 22, 24) »> Ista = [30, 32, 34] ee operator is used 1 concatenate >> Ast = Ista ‘three individual lists to get a new i +1st2+1st3 ie ees (12,24, 20, 22, 24, 30, 32, 34] list types. You i «5 that both the operands must be of li P toa list. For example, following ‘expression will result INFORMA cg Consider the following examples % >>> Ist1 = [10, 12, 14] ‘See errors generated when a anh >>> Ist +2 Ys other than att is added vo gt Traceback (most recent call last): File "", line 1, in Ast1+2 TypeError: can only concatenate list (not “int") to list >>> Ist + "abe" Traceback (most recent call last): File "", line 1, in Ast1+"abc" ‘TypeError: can only concatenate list (not "str") to list 7.3.2 Repeating or Replicating Lists Like strings, you can use * operator to replicate a list e fend tered Mil, 5] specified number of times, 24 Like strings, if you give : List = [5, 6, 8, 11, 3], following expression will reverse it : 7.2 Extract two list-slices out of a given list of numbers. Display and print the sum of elemenss rogram INFORMATICS pracy, lees [:: -1], it will reverse the list eg, fda 4 list % >>> List [11-1] See, List reversed [3, 11, 8, 6, 5] Le lisslice which contains every other element of thelist between indexes 5 015. Program st display the average of elements in second list slice that contains every fourth elemen gp li The given list contains numbers from 1 to 20. Ast =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 29] sle1=Ist[5 : 15:2] slc2=1st[::4] sum = avg =@ print ("Slice 1") forainslc1: sum+=a pease =) Sample run of above program is print () print ("Sum of elements of slice 1:", sum) slice 1 print ("Slice 2") : 68101214 ee: Sum of elements of slice 1: 50 for ain slc2 : oe agli 1591317 eee) ‘Average of elements of slice 2:9 print () avg = sum /len(s1c2) print (“Average of elements of slice 2:", avg) Using Slices for List Modification You can use slices to overwrite one or more list elements with one or more other elemen’ Following examples will make it clear to you : In all the above examples, we have >>> L=["one", "two", “THREE"] >>> L[@:2] =[@, 1] «——______ assigning new values to list slice >>> (eereeey Ge Notice, what the list changes 1, >>> L=["one", "two", "THREE"] >>> L[0:2] ="a" >>> ['a", "THREE"] @ Notice, what the list changes to, assigned new values in the form of a sequence. The Vl" being assigned must be a sequence, i.c,, a list or String or tuple etc. ust MANIPULATION pn . ample, following assignment is also valid, ic for Sao ia [2:1 = "624" String is also a sequence it yt en iM >, 3) (60105) aaa putityoutry t© assign a non-sequence value to alist slice such as a number, Python will, givean ity lg 2iSe* ae 345 is a number, not a sequence pola [2? pice ", Line 1, in 345 n only assign an iterable tu [2 typetrror: cal gut here, you should also know something. If you give a list slice with range much outside the tength of the list, it will simply add the values at theendeg, po ld=[1, 253] +20] = "abcd" *——————. no error even though list slice limits are outside pla [18 : 20] = "at the length. Now Python will append the letters por ll to the end of list LI. [15 253A obsess Working with Lists Now that you have learnt to access the individual elements of a list, let us talk about how you can perform various operations on lists like : appending, updating, deleting etc. | *opending Elements to a List ; ; You can also add items to an existing sequence. The append() method a: end of the list. It can be done as per following format: ee L.append(item) Consider some examples : >>> sti =[10) 42,14] ab >>> Ist append(16) >>> Asta ‘The element specified as argument to append() is (22, 22, 14, 16] a added at the nd of existing ist idaes 8 INFORMATICS PACT ts Deleting Elements from a List You can also remove items from lists. The del statement can be used to remove an ee item, or to remove all items identified by a slice. Vid Itis to be used as per syntax given below : del List [ ] # to remove element at index del List [ : ] _ # to remove elements in list slice Consider following examples : >>> Ist =[1, 2, 3, 4, 5, 6 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] >>> del 1st[10] Delete element at index 10 in list namely lst. >>> Ist See 11 got deleted, Compare with list above [1 2, 3,4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20] >>> del 1st[1@:15] <—————_ polete all elements between indexes 10 to 15 in list >>> Ist namely Ist. Compare the result displayed below [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 17, 18, 19, 20] Ifyou use del only e.g., del Ist, it will delete all the elements and the list object to, After this, no object by the name Ist would be existing. You can also use pop( ) method to remove single element, not list slices. The pop( ) method removes an individual item and returns it. The del statement and the pop method do pretty much the same thing, except that pop method also returns the removed item along with deleting it from list. The pop( ) method is used as per following format : List.pop( ) #index optional; if skipped, last element is deleted ‘Consider examples below : >>> Ist =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] >>> Ast -pop() ea ee i 7 >>> Ist.pop(10) te i = un i mx The pop( ) method is u only when ‘ou want to store the element being deleting { faeces ny. item1 = L.pop() ‘# last item item2 = L.pop() ved to make a copy of a list and you you need Benerally tend to do it using aes, using assignment, e.g., ete Trying to make copy of lst @ in list b not make B as @ duplicate list ofa ; rather just like Python fal pay make label b to point to where label a is pointing to, ie, as || i . is djcent igure a rs e long as we do not modify lists. Now, if you make char work fine a a F i il per because a and D are like aliases for the same list, See ie ene yar [ts 23] pp bea >» alt] =5 ya 155551) See, list b is also reflecting the ieee (1,5, 3] «e along with lista, list b also got modified. What if you want that the gy lst b should remain unchanged while we make changes in lista ? ‘huts you want both lists to be independent of each other as shown in sjacnt figure. For this, you should create copy of list as follows : b=list(a) ‘ow a and b are separate lists. See below : >>>a=[1, 2, 3] >>> b= List(a) >>> alt] = ma {1,5,.38 >» ist isnot reflecting the cha ee ete » Ths me independent copy of a list is made via list ) method; assigning list to another identifier just {thon als ofers many bull functions and methods for ist manipulation. Youhavesleat many ith one such method len( ) in earlier chay In this chapter, you A ee ‘powerful list methods of Python used for list manipulation, ; any object that i is actually an i you create in Python is a Dat? , cnethod names() INFORMATICS Practice s ” we are referring to as List only (no angle bra, .ce List with a legal list (ie. either a list liter ora; aly In the following examples, the meaning is intact i.e., you have to replat object that holds a list). Let us now have a look at some usefull buill 1. The index method This function returns the index of first matched item from the list. It is used as per fo format : loving {in list manipulation methods. List.index (>> Lindex (18) <——__retums the index of fist value 18, even if 1 there is another value 18 at index 4. However, if the given item is not in the list, it raises exception value Error (see below) List. index(33) ? Traceback (most recent call last): File “cipython-input-60-@38fc9bf9cSc>”, line 1, in - list. index(33) ValueError: 33 is not in list i IS swine: tthe append( ) method adds an item to the end of ie st WANIPULATION am s i, nethod at is also used for adding multi i etho ee ple elements (given in the form ofa toalist. ' eet ioe from append). First, let us understand thee feae is the working of extend( ee putts pout the difference between these two functions, 4 a i eee function works as per following format: 4 exten | ret | jst extend() = ‘ates exactly one element (alist type) and returns no value extend() takes list as an argument and aj ippends all of the elements of the .ct on which extend( ) is applied. argument list is extend sp the list obje consider following example : yo th= [By 'C] yp t= Ee] Extend thelist 4, by adding all elements of (2 >» theextend(t2) stl See the elements of list #2 are added at the end of list #1 [a,'0,'¢,'d,"e) vot. z But list 12 remains uncha ss te] Re oat = Theabove example left lst 2 unmodified. Like append(), extend() ees Consider following example : a Pring to assign the result of >> t3 = tl.extend(t2) fe . uh Dm m5 INFORMATICS PRACT cts “A to enter mutiple element the ice sq! If tr a2, 141) AE fof rte a Peay wt ad the complete Tt 8 one element, it will show that now it —— yen au Peck the fengt of he Hh tras 5 elements, Because newly added list [12, 14] is treated as single Oe yp ti -append( ppt [1 3, 5. 20 [22 >>> Len(t1) 5 tees ‘The extend() cannot add single element; it xtend(10) “~ equines ast as argue it call last)+ line 1, in >>> t2.e Traceback (most recen File "cpyshell#7>"> t2.extend(10) object is not iterable typetrror: “int! yoo tavextend([12, 14]) —_ rad 4 po>t2 Tither provide lst value or a list object [7, 8, 12, 24] po9t3 = [28, 46] poo t2.extend(t3) ppot2 [7, 8, 12, 14, 22, 40] » ice, extend( ) added the individ “>> len (2) elements of the list argument 5. ee uhh earlier had elements has now including 2 elements of st MANIPULATION yu we can say that ; tion insert( ), ill insert element x at th ind (2 oe ) “il t element ‘tira pi to length of a), x)_ will insert element x at the end of the list - index P gteansere( 6n( the list ; thus it is equivalent to listappend(x), oe If index is greater than len(tst, the object is simply ver, index is less than zero and not equal to any of the valid negative indexes of yjpoweret ) # » ele = t1.pop(@) <——____ Remove ‘Bed, 'U] >> ele2 = t1.pop() >> ele2 if v >t _ 4, INFORMATICS, PRACTICES , sy) 6. The remove method While pop() removes an element whose position is given, what if you know the value gp element to be removed, but you do not know its index or position in the list ? Wel}, Py the thought it in advance and made available the remove( ) method. thoy, The remove ) method removes the first occurrence of given item from the list. It is useg ue following format : ee ~ List.remove () Takes one essential argument and does not return anything ‘The remove( ) will report an error if there is no such item in the list. Consider some examples, >>> ti=[a,'e, i, pd, ‘a, dP] >>> t1.remove(‘a') a i Fit occurence of ais removed fram thelist [e,'t, pd‘, ds PT >>> t1.remove(‘p') >>> t1 pee Eine i (eid, a, ‘d, 'P') Trying to remove an element which is >>> tL remove('k’) not present inthe list, raises ero. First occurrence of ‘p's removed from the list Traceback (most recent call last): File “", line 1, in th pemove(‘k’) ue = _—-ValueError: list.remove(x):xnotinlist JNPULATION ble types ? ited mutal ists © arts of ae ge counterp 4 a sm, ays of creating rent We ae 2 ues © an we have in a ist? Do ym eo? tobe the same typ vol jal elements of lists are 02% and changed ? , create the following lists ? Te ‘pong expressions: to) 20) Cre leo) 2-1) Walaa (2 [2] +1) ]] “epence? What if the sequer Sin What if the sequence is. Wit does 2 +b amounts to if a its 2 " not retum anything. ca To sort a list in decreasing order usir 9. The reverse method The reverse ) reverses the items of the list. This is done “in place”, / Le., it does not create a new list. The syntax to use reverse method is : List. reverse() ~ Takes no argument, returns no list ; reverses the list ‘in place’ And does not return anything, For example, >>> tl Ce, i, “aya, 'd,'p) >>> th reverse() >>> tL —————_ The reversed list Cp, 'd,'a,'d, 't','e] >>> t2 = [3, 4, 5] >>> t3 = t2.reverse( ) >>> 13 + 5 stores nething as revert} >>> t2 ———— (5, 4, 3] 10. The sort method The sort) function sorts the items of the list, by default in increasing order. This is done “in place’, ie, it does not create a new list. It is used as per following syntax: List.sort() For example, oootle (et, ‘qs 'a ad. PT) >>> t1.sort() ee ees ioe >>>tl ‘Tae ted a] Like reverse( ), sort() also performs INFORMATICS PRAG Tle ‘ tof element along, with its index inthe j list, Program to find minimum element from a lis 1st « eval (anput(“enter List : ")) length = len(1st) min_ele = 1st[@] min_index = @ for i inrange(1, length-2) ¢ if Ist[i] < min_ele = min_ele = 1st[i] min_index = 4 print("Given list is: ") 1st) print "The minim elenent of the given list is: print(min_ele, “at index", min_index) [2, 3, 44-2) 6, -7) By 11, -9, 11) a Enter list : Given Vist is : (2, 3, 4, -2) 6) -7s 8, 11, -9, 11] The minimum element of the given list is: -9 at index 8 Program to calculate mean of a given list of numbers. De : — “for inrange(@, length-1) : n4=1st[4] ust MANIPULATION oo" 0 sample runs of above program are being given below : im : eer ist: (2, 8 9, 1, -55, -11, a 78, 67] en " grenent. to be searched for : 1 ch at index 5 Beer vist: (2, 8) 9) My -55y cap 22, 78, 671 ier element to be searched for : -2 tp not found in given Vist (F765 Program co count frequency of a given element ina list of numbers, |/ Hoon st eval (inpire("ententice ce length = len(1st) element = int (input(“Enter element :")) count = @ for i in range(®, length-1' if element == Ist[i]: count += 1 if count ==@ : print(element, “not found in given list") else : print(element,"has frequency as", count, "in given list") Sample run of above program is given below : pee Bomar re2 3; 55° 25,7, 51 mr element: 257 INFORMATICS PCI & if element not in unig and element not in dup1: ita / for j inrange(i, length): if element == Ist[j]: count else: #when inner loop - for loop ends print("Element", element, "frequency:", count) if count == 1: uniq. append (element ) else: dup1.append(element) when element is found in unig or dup] lists 3 print (“Original list", 1st) i isthe These print() statements are not print ("Unique elements list", uniq) eee print("Duplicates elements list", dup1) Seis al2y3s24, 5, 3. 6, 7, 3,5, 2, 7, 1, 9, 2] Element 2 frequency: 3 Element 3 frequency: 3 Element 4 frequency Element 5 frequency) : Element 6 frequency Element 7 frequency: 2 Element 1 frequency: 1 Element 9 frequency) Original list [2, 3, Areas e673) nee Unique elements list (872, 9] Duplicates elements list eases a7) 1, 9, 2] _ yANIPULATION ff recurs the number of items (Court) in the lise r, ee ator intells if an element is present in the ist op adds one list to the end of another. The * operat naan part ofa list; lis slice isa list in itselp ree ft ries elements falling ben ot and not sie Problems goals diferent from strings when both are sequences ? Son The lists and strings are different in following ways : () The lists are mutable sequences while strings are immutable, {In consecative locations, strings store the individual characters while lst stores the references of its elements. (ii) Strings store single type of elements — all characters while lists can store elements] to different types. belonging 2 Wat are nested lists ? ‘sation. When alist is contained in another list as a member-element, itis called nested list, eg, a=[2, 3, [4, 5] Theabove lista has three elements — an integer 2, an integer 3 and a list [4 5], hence itis nested list. * Wat does each of the following expression evaluate to ? Solution. Suppose that L is the list [These”, “are”, “a”, Sse", “words"], “that”, “we”, “will”, “use"] @ fee int (0 “few in L(3] (fay) + L[3y o Ufa] echoes Le: Bee 0 see A (0) True. String “few” is part of list, which is at the index 3 of List L ie, 1(3), @ ~~ [e(a}} = C'are'] L[3] = [ "few, ‘words'] [L[1]] + L[3] = Care’, ‘few, ‘words'] (0) ['that’, ‘we’, ‘will, ‘use’] () [ These’, ‘a, "that!, ‘will'] 4. What does each ofthe following expressions evaluate 10? Suppose that L is the list ["These”, ["are”, “a"], ["few", “words"], that", “we", “will”, “use”), (a) len (L) () U[3:4] + L422] (c) “few” in L[2:3] (@® “few” in [2:3] [2] © “few” in L[2] () L(2){4:] (ge) U(2) + L12] Solution. @ 7 aes (®) [3:4] = ['that’] [3:4] + L[2:2] = ['that, [are 'a']] (0) False. The string “few” is not an element of this range. L[2 3] returns a list of elements L-> [[few’, ‘words’]}, this is a list with one element, a list. a ‘L{2:3] list is a list [“few”, “words”] which has a member “few” init list few’, ‘words'], “few” is an element of this list. = puLATION ey NANI yst salt sil pos < en (L) # a gu = sum + L[pos] pos = pos +2 int (Sum ) goation pos = @ =0 end pos < len (L) af L[pos] ¥2 == 1: sum = sum + L[pos] pos = pos +1 print (sum ) «Examine the following code : pos = 0 odds = evens = @ length = Len (num List) while pos < length : if numlist[pos] % evens = evens + 1 else : odds = odds + 1 pos = pos +1 if odds > evens : print ("Balanced oddity") (®) What és this program calculating ? sep ofintegers, Ly torte code to add the integers and display the sum, nals L. vals of integers, L, torte code to calculate and display the sum ofall the odd numbers in thelist 4 ip t. nunlist = eval(input ("Enter list: (®) What does the program for the list (1, (©) What does the program print for the list (2, 5, 2,5: Solution, # start of list # initial sum # loop through entire list # add current item to sum # move to next item in ilst # the answer # start of list # initially no sum # Loop through list # this is an odd number # so add it # next item in list # the answer » 5,2,3,6,6,91? 6, 6, 9] ? How can vee fr this? Solution. Lista = eval (input( listB = eval (input("enter list2: Jeni = len(listA) Jen2 = len(listB) for ain range(1en1) : ele = listala] if ele in list8 = "enter list] print ("overlapped") break else : #loop ends normally, not because of break print("separated”) 11. Write a program to find the second largest number of @ list of numbers. Solution. Ast = eval (input("Enter list 2") Jength = len(1st) 4 though logically not fair | biggest = secondbiggest = Ast[0] for i in range(1, length): 3 if Ist[i] > biggest: 2 ee | | secondbiggest = biggest 2 biggest = 1st[i] __ elif Ist[i] > secondbiggest: a ‘secondbiggest = Ist{i] - print(“Largest number of the list :", biggest) ceil _ print("Second Largest number of the List 7, secondbiggest ) 12. Writea program that i - z we fthets. fait of rarest Sica ead ie ee i aNtPULATION ui of : RY eS oo ‘a mutable sequence cof Python that can store objects of ‘ony type, » An integer voile thot is used fo ident the postion of an element a The sequential accessing cof each of the elements in a list, A lst created from o list containing the requested elements, isan yeh: Short Answer Questions/Conceptual Questions | Discuss the utility and significance of Lists, briefly. : 2 What do you understand by mutability ? What does “in place” memory updation mean ? 3. Sart with the list [8, 9, 10]. Do the following using list functions : (@) Set the second entry (index 1) to 17 (}) Add 4, 5 and 6 to the end of the list (9 Remove the first entry from the list (@ Sort the list (©) Double the list (Insert 25 at index 3 4 Ifais (1, 2, 3] (©) what is the difference (if any) between a * 3 and [a, a, a]? @) isa*3equivalenttoata+a? ve (©) what is the meaning of af1:1] = 9? @ what's the difference between. a[l:2] = 4 and a[i:1] = 42 'NFORMATICs Py Type B : Application Based Questions 1. What is the difference between following 'W0 expressions, if Ist is given as [1, 3, 5) () Ast *3 (i) Ist *= 3 2. Given two lists Ae eae Las["this", ‘is’, ‘a’, ‘List'], L2= ["this",.[“4s", “anothent }asideea Which of the following expressions will cause an error and why ? (@) Lis=L2 (}) L1.upper( ) (c) L1[3]-upper( ) @ L2.upper( ) (© (2[1]-upper() — @)._ L202] 12] upper( ) 3. From the previous question, give output of expressions that do not result in error. 4. Given a list Li = [3, 45, 12, 257, [2, 1, 0, 5], 88) (@) Which list slice will return [12, 25.7, [2, 1, 0, 5] (®) Which expression will return [2, 1, 0, 5] (Q) Which list slice will return [2, 1, 0, 5] | (@ Which list slice will return [4.5, 25.7, 88] 5. Given a list L1 = [3, 4.5, 12, 25.7, ]2, 1, 0, 5], 88], which function can change the list to : (@) 3,45, 12, 257, 88] g @ (3,45, 12, 25.7] © [12 1, 0,5}, 88] as 2 6. What will the following code result in ? > 25.4 . Li = [2, 3, 5, 7, 9] print (L1 == L1.reverse( ) ) -my_list=["p', 'r’, 'o', 'b',

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy