Additional Operations with Sequences
6.4 Operations with Sequences
6.4.1 Max() and Min() Functions
The max() and min() built-in functions identify and return the maximum and minimum elements from a given set. The criteria for identifying the
>>> 'Hello, how are you?'.count('o') [1]
3
>>> ff = [3, 2, 5, 2, 4, 7, 2] [2]
>>> ff.count(3) [3]
1
>>> ff.count(2) 3
>>> a = 5, 10, 15, 20 [4]
>>> b = 5, 11, 14, 1 [5]
>>> c = 5, 10, 14, 2500 [6]
>>> a > b [7]
False
>>> a < b [8]
True>>> b > c [9]
True>>> c < a < b [10]
True
>>> aa = ['aa', 'ab', 'ac'] [11]
>>> bb = ['bb', 'bb', 'cc'] [12]
>>> cc = ['aa', 'ab', 'ad'] [13]
>>> aa < bb [14]
True>>> aa < cc [15]
True
>>> aa[2] < cc[2] [16]
True
>>> qtt = '''What everybody echoes or in silence passes by as true today may turn out to be falsehood tomorrow, mere smoke of opinion, which some had trusted for a cloud that would sprinkle fertilizing rain on their fields'''
>>> qtt.count('or') [17]
3>>> len(qtt)
209>>> qtt.index('or') [18]
22
>>> qtt.index('or', 23) [19]
92
>>> qtt.index('or',93) [20]
146>>>
Fig. 6.9 Python Interpreter sequence illustrating use of comparison and other operations with sequences
110 6 Additional Operations with Sequences
maximum/minimum value can be specified through a key. The Python Interpreter sequence in Fig.6.10illustrates their use.aa [1] is a tuple of numbers; b1 (=max (aa)) is returned as the maximum amongst them (=3) in [2]. Similarlyb2 (in aa) is the minimum (at−1.2) amongst them. The maximum amongst the absolute values of the elements inaa is 7.1 with the key as abs(x) for x; this maximum value is assigned toc1 in [3]. The minimum of the absolute values (=0.8) is assigned to c2.
The reciprocals of the elements ofaa form the basis to decide the maximum and the minimum in [4]. With this the maximum value is assigned to d1(=1/0.8) and minimum to d2 (=−1/1.2). Any other criterion/metric can be used as the key to identify the min/max values. Use of max as max (2, 3, 2.5, −1.2, 0.8, −7.1)
>>> aa = (2, 3, 2.5, -1.2, 0.8, -7.1) [1]
>>> b1, b2 = max(aa), min(aa) [2]
>>> b1, b2 (3, -7.1)
>>> c1, c2 = max(aa, key = lambda x:abs(x)), min(aa, key
= lambda x:abs(x)) [3]
>>> c1, c2 (-7.1, 0.8)
>>> d1, d2 = max(aa, key = lambda x:1/x), min(aa, key =
lambda x:1/x) [4]
>>> d1, d2 (0.8, -1.2)
>>> max(2, 3, 2.5, -1.2, 0.8, -7.1) [5]
3
>>> min(2, 3, 2.5, -1.2, 0.8, -7.1, key = lambda x:1/x) [6]
-1.2
>>> ff = 'Karthik', 'Kala', 'Karun', 'Lan', 'Sarani' [7]
>>> f1, f2 = max(ff), min(ff) [8]
>>> f1, f2
('Sarani', 'Kala')
>>> f3, f4 = max(ff, key = lambda x: len(x)), min(ff, key
= lambda x: len(x)) [9]
>>> f3, f4
('Karthik', 'Lan')
>>> from demo_5 import marks1 [10]
>>> bb = marks1.st [11]
>>> e1, e2, e3 = max(bb, key = lambda x:len(x[0])), max(bb, key = lambda x:x[0]), min(bb, key = lambda
x:x[1]) [12]
>>> e1, e2, e3
(('Karthik', 77, 78, 79, 80, 81), ('Sarani', 76, 78, 82, 83, 84), ('Lan', 65, 86, 66, 67, 68))
Fig. 6.10 Python Interpreter sequence illustrating use of max() and min() functions
directly in [5] yields the maximum value (=3). Same holds good of the min () function as well. As an extended use the max/min criteria can be specified through a key as done in [6].
ff in [7] is a tuple of names. max(ff) is decided with the criteria a < b < c <
⋯ < x < y < z the comparison being carried out starting with the first letter.
Sarani (=f1) is returned as the max—the choice being based on the first letter itself [8]. Kala (=f2) is the minimum; the selection based on the first letter will have karthik, kala, and karun. The second letter—being ‘a’ in all of them—does not change the scenario. At the third stage‘l’ in kala (=f2) decides the choice.
[9] uses the length of the name—number of characters in it as the basis to decide the maximum (f3 = karthik) and minimum (f4 = lan). The marks-list from demo_5 is imported [10] and assigned to bb in [11]. It is the same as that in Fig.5.16. the max()/min() can be specified in different ways and extracted. [12]
shows three examples. Karthik is the student with the longest name. His data is assigned toe1. Alphabetically Sarani comes last; her data is assigned to e2. The mark scored in Physics is the basis for selection of e3. The candidate with the lowest marks scored in physics islan; his data is assigned to e3.
6.4.2 Additional Operations with Sequences
The Python Interpreter sequence in Fig.6.11illustrates the use of some additional operations with sequences.aa in [1] is a list of strings. del aa[3:9] in [2]
deletes all the elements fromaa[3] to aa[8] (inclusive) from aa. aa[2]=‘2C’ in [3]
redefines the value of aa[2] as can be seen from the lines following. The usage here is different from the assignment ‘cc = aa[2]’ where cc is assigned the value of aa[2] without altering aa in any way. Similarly ab[−1] (=‘7H’) in [12] replaces the last element ofab(=‘h7’) in [7]. The new value of ab is in [13]. ab.append(ab1) in [6] appendsab1 [5] to list ab [4]—this is possible, ab being an iterable. The method append() appends a single element to the list; the appended element gets inserted into the list as its last (rightmost) element. [7] shows ab with ab1 appended to it.ab is restored in [8] to its previous value in [4] by deleting the last element inab—that is ab1.
ab.extend(ab1) in [10] enhances ab by appending all the elements of ab1 to it in the same order at one go. In contrastab.append(ab1) in [6] appends ab1 as a single entity toab.
Method append() is useful if the elements to be appended are formed one by one (as in a loop). But if the elements (more than one) to be appended are known at a stretch method extend() is a better alternative.
aa is defined afresh in [14]. del aa[3:9:2] in [15] deletes all elements in aa starting withaa[3] and going up to aa[9] at interval of 2. (start, stop, step) set is similar to that in slicing (in Sect.6.1). The truncatedaa in [16] is defined afresh in [17]. Elements ofan of three elements in [18], replace three elements in aa through [19]. Here again the set of three elements in it—aa[3] to aa[9] at the interval of
112 6 Additional Operations with Sequences
>>> aa =['a0','b1','c2','d3', 'e4', 'f5', 'g6', 'h7',
'i8', 'j9', 'k10', 'l11'] [1]
>>> del aa[3:9] [2]
>>> aa
['a0', 'b1', 'c2', 'j9', 'k10', 'l11']
>>> aa[2] = '2C' [3]
>>> aa
['a0', 'b1', '2C', 'j9', 'k10', 'l11']
>>> ab = ['a0', 'b1', 'c2', 'd3', 'e4'] [4]
>>> ab1 = ['f5', 'g6', 'h7'] [5]
>>> ab.append(ab1) [6]
>>> ab [7]
['a0', 'b1', 'c2', 'd3', 'e4', ['f5', 'g6', 'h7']]
>>> del ab[-1] [8]
>>> ab [9]
['a0', 'b1', 'c2', 'd3', 'e4']
>>> ab.extend(ab1) [10]
>>> ab [11]
['a0', 'b1', 'c2', 'd3', 'e4', 'f5', 'g6', 'h7']
>>> ab[-1] = '7H' [12]
>>> ab [13]
['a0', 'b1', 'c2', 'd3', 'e4', 'f5', 'g6', '7H']
>>> aa =['a0','b1','c2','d3', 'e4', 'f5', 'g6', 'h7',
'i8', 'j9', 'k10', 'l11'] [14]
>>> del aa[3:9:2] [15]
>>> aa [16]
['a0', 'b1', 'c2', 'e4', 'g6', 'i8', 'j9', 'k10', 'l11']
>>> aa =['a0','b1','c2','d3', 'e4', 'f5', 'g6', 'h7',
'i8', 'j9', 'k10', 'l11'] [17]
>>> an = ['3D', '5F', '7H'] [18]
>>> aa[3:9:2] = an [19]
>>> aa
['a0', 'b1', 'c2', '3D', 'e4', '5F', 'g6', '7H', 'i8', 'j9', 'k10', 'l11']
>>> aa = ['a0', 'b1', 'c2', 'e4', 'g6', 'i8', 'j9', 'k10', 'l11']
>>> for jj in range (len(an)):aa.insert(3+2*jj,an[jj])[20]
... >>> aa
['a0', 'b1', 'c2', '3D', 'e4', '5F', 'g6', '7H', 'i8', 'j9', 'k10', 'l11']
>>> an.pop(1) [21]
'5F'>>> an [22]
['3D', '7H']
(a)
Fig. 6.11 a Python Interpreter sequence illustrating use of some methods and operations with sequences (continued in Fig.6.11b) b Python Interpreter sequence illustrating use of some methods and operations with sequences (continued in Fig.6.11a)
two—that is aa[3], aa[5], and aa[7]—is replaced; ‘d3’, ‘f5’, and ‘h7’ are replaced by‘3D’, ‘5F’, and ‘7H’ respectively. Needless to say, size of an here is to be the same as that required for the substitution.
insert(jj, x) will insert x at the jjth location in aa. An alternate way of insertingan into aa (done above) uses insert() in a loop [20]. But the insert operation in [19] is more elegant and compact. an.pop(1) in [21] popsan(1). With that,an[2] (=‘7H’) in (18) takes the place of an[1] as can be seen from [22]. aa andan have been redefined in [23] and [24] as lists—the latter being an empty one.
an.append (aa.pop(jk)) pops the jk th element in list aa and appends it to an.
With that aa(jk + 1) moves to aa[jk] and number of elements in aa reduces by one. The popped element is appended toan. For jk = 3, 5, and 7 in succession the loop in [25] executesan.append (aa.pop(jk)). Table6.1clarifies the steps in the process. The truncatedaa and the new an are in [26] and [ 27] respectively.
aa.remove(x) removes the first occurrence of element x from list aa. If x is not present in aa a ‘ValueError’ is returned. The list aa has been restored in [28]. aa.remove(‘d3’) in [29] removes the element ‘d3’ from it as can be seen from the updated value ofaa in [30]. bb is a list of integers in [31]. bb.remove (2) in [32] removes the first occurrence of the integer ‘2’ from the list; the new value of bb is [3, 5, 2, 7, 1] as in [33]. bb.remove(2) in [34] removes the
>>> aa =['a0','b1','c2','d3', 'e4', 'f5', 'g6', 'h7',
'i8', 'j9', 'k10', 'l11'] [23]
>>> an = [] [24]
>>> for jk in range(3, 9, 2): an.append(aa.pop(jk)) [25]
...
>>> aa [26]
['a0', 'b1', 'c2', 'e4', 'f5', 'h7', 'i8', 'k10', 'l11']
>>> an [27]
['d3', 'g6', 'j9']
>>> aa =['a0','b1','c2','d3','e4','f5','g6', 'h7', 'i8',
'j9', 'k10', 'l11'] [28]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list (b)
Fig. 6.11 (continued)
114 6 Additional Operations with Sequences
remaining‘2’ from bb leaving it as [3, 5, 7, 1] in [35] without any more ‘2’s within.
Hence another bb.remove(2) in [36] returns a‘ValueError’.