Python Notes PDF
Document Details
Uploaded by TimeHonoredBanjo2756
null
null
null
Tags
Summary
This document provides Python notes on the random module and lists. It covers various list operations. It's suitable for high school or introductory programming courses.
Full Transcript
Python Notes Class XI List random module Word random in English means unpredictable, unspecified or without any fixed pattern. Example of event in real life: tossing of coin, rolling of dice and picking a card from a dec...
Python Notes Class XI List random module Word random in English means unpredictable, unspecified or without any fixed pattern. Example of event in real life: tossing of coin, rolling of dice and picking a card from a deck of cards. In Python we have module random, which generates pseudo random numbers (either int or float). We will consider four functions from the random module: 1. randint() randint(start,stop): generates a random integer between start and stop including start and stop. Both start and stop are integer type and start stop and step>0 randrange(9, 90, -3) – will trigger an error since start < stop and step stop then a random floating value is generated between stop and start. This is unlike randint() and randrange() functions, when start is greater than stop, an error is triggered. Examples are given below: from random import uniform for x in range(8): num=uniform(1, 9) #generates a random value between 1 & 9 print(round(num, 4), end=' ') Running of the program produces following output: 1.7245 6.2180 6.2501 4.4136 8.8899 1.5373 6.7080 6.8809 from random import uniform for x in range(8): num=uniform(9, 1) #generates a random value between 9 & 1 print(round(num, 4), end=' ') Running of the program produces following output: 8.0354 2.6453 4.1432 2.8452 3.9596 2.9638 3.1555 3.9742 uniform() function with single parameter or without any parameter will trigger an error. FAIPS, DPS Kuwait Page 2 of 18 © Bikram Ally Python Notes Class XI List List In Python a list is special type of variable used to represent many values under one variable name in the RAM (Random Access Memory - main storage). A variable of fundamental data type like int or float or str or bool or complex will store only one value under one variable name. A Python list type variable will store many values under one variable name. A list in Python is either a homogeneous collection or a heterogeneous collection. A list may be created in the following way: listname=[value1, value2, value3, …] >>> list1=[10, 20, 30, 40, 50] >>> list2=[2.3, 4.5, 6.7, 8.9] >>> list3=[15, 2.5, 35, 4.5] >>> list4=['Sun', 'Mon', 'Tue', 'Wed', 'Thu'] >>> list5=[10, 'DILIP', 89.0, 'B1'] >>> list6=[] #creates an empty list, without any value >>> list7=list() #creates an empty list, without any value The lists list1 , list2 and list4 contains homogeneous values. The list list3 and list5 contains heterogeneous collection. The list list6 and list list7 is an empty list (the two lists do not contain any value). Every value stored in the list is called an element of the list. 0 1 2 3 4 Every element in the list is assigned an index starting from 0 list1 10 20 30 40 50 (zero). The first element in the list from the left is assigned -5 -4 -3 -2 -1 an index 0, the second element in the list from the left is assigned an index 1, the third element in the list from the 0 1 2 3 left is assigned an index 2 and last the last element in the list list2 2.3 4.5 6.7 8.9 (from left) is assigned (number of elements - 1) as an index. -4 -3 -2 -1 Python supports negative index. First element from left will have index starting from length of list. Last element of a list 0 1 2 3 will have an index -1. Traversing a list from left to right, list3 15 2.5 35 4.5 index is incremented by 1. Traversing a list from right to -4 -3 -2 -1 left, index is decremented by 1. 0 1 2 3 4 A list in Python can contain any list4 'Sun' 'Mon' 'Tue' 'Wed' 'Thu' type of data (int / float / str / …) -5 -4 -3 -2 -1 but an index of a list is always an int type (either a constant or a 0 1 2 3 variable or an expression). Index list5 10 'DILIP' 89.0 'B1' always starts from left. Next index -4 -3 -2 -1 is one more than the previous index. If index starts from right, >>> print(list1) previous index will be one less Displays [10, 20, 30, 40, 50] than the current index. Displaying a list with print() function, by >>> print(list2) default will display the list from Displays [2.3, 4.5, 6.7, 8.9] left to right including the delimiter [] and values will be separated by >>> print(list3) comma. String values present in Displays [15, 2.5, 35, 4.5] the list will be displayed enclosed with single quote ('). >>> print(list4) Displays ['Sun', 'Mon', 'Tue', 'Wed', 'Thu'] FAIPS, DPS Kuwait Page 3 of 18 © Bikram Ally Python Notes Class XI List >>> print(list5) Displays [10, 'DILIP MEHTA', 89.0, 'B1'] >>> print(list6) Displays [] since alist6 is an empty list (does not contain any element / value) As mentioned earlier, print() function will display the entire list from left to right. But when working with a list, we need to access the individual elements / values stored in the list. Each element of a list can be accessed as: listname[pos] Data type for list pos must be an int. If a list has n elements then n indices are: 0, 1, 2, …, n-3, n-2, n-1 (non-negative index starting from 0) -n, -(n-1), -(n-2), …, -3, -2, -1 (negative index) If index is out of range (access an element with an invalid index), will trigger a run-time error. 0 1 2 3 4 list1 10 20 30 40 50 -5 -4 -3 -2 -1 Statement like, print(list1) or print(list1[-7]) will trigger run-time error. One needs to access an element a list for the following: To update the value stored in the element To display the value stored in the element To use the value stored in the element for some calculation / processing >>> alist=[9329, 35.8, 'RIVER', 4783, 58.2, 'OCCEAN'] >>> for k in range(6): print(mylist[k], end=' ') Displays the list from left to right as: 9329 35.8 RIVER 4783 58.2 OCCEAN Control variable k of the for-loop generates the index for every element present in the list alist. Instead one can also use while loop also: >>> alist=[9329,35.8,'RIVER',4783,58.2,'OCCEAN'] >>> k=0 >>> while k> for k in range(1,7): print(alist[-k], end=' ') Displays the list right to left: OCCEAN 58.2 4783 RIVER 35.8 9329 Using while-loop: >>> k=1 >>> while k> for ele in alist: print(ele, end=' ') Displays the list left to right: 9329 35.8 RIVER 4783 58.2 OCCEAN In this case, control variable ele represents every element / value present in the list alist. Using a list name as an iterable object is only possible using for loop. Using while-loop one can only use index method to access the elements present in a list. Using operators and keyword del with a list Creates a new list >>> marks=[] #marks=list() creates an empty list >>> print(marks) = Displays [] >>> marks=[24, 'TARUN', 'COMP SC', 56, 25] >>> print(marks) Displays [24, 'TARUN', 'COMP SC', 59, 28] Assigns a value to an element of a list (updates value stored in an element) >>> marks=[24, 'TARUN', 'COMP SC', 56, 25] >>> marks=59 = >>> marks=28 >>> print(marks) Displays [24, 'TARUN', 'COMP SC', 59, 28] Creates an alias since list is a mutable type >>> stu1=[12, 'RAHUL', 64] >>> stu2=stu1 Now updating stu1, will update stu2 and vice versa. This is because list is a mutable type. = >>> stu1+= #updates stu2 >>> stu2+= #updates stu1 >>> print(stu1, stu2) Displays [12, 'RAHUL', 64, 28, 92] [12, 'RAHUL', 64, 28, 92] Two lists contain identical (same) values (elements). Joins to two or more lists (list concatenation) >>> list1=[24, 'TARUN', 56] >>> list2=[25, 81, 'B2'] >>> list3=list1+list2 >>> print(list3) + Displays [24, 'TARUN', 56, 25, 81, 'B2'] Only two (or more) lists can be concatenated >>> alist=[10, 'AB', 7.2] >>> alist=alist+(20, 'CD') Above statement will trigger an error. Updates an existing list by appending values from another iterable object >>> stu=[24, 'TARUN'] >>> stu+=[25, 81] >>> print(stu) Displays [24, 'TARUN', 56, 25, 81] >>> stu+=('B1', 'PASS') >>> print(stu) += Displays [24, 'TARUN', 56, 25, 81, 'B1', 'PASS'] >>> alist= >>> alist+={'X':5, 4:2.5} >>> print(alist) Displays [3, 'X', 4] keys present in the dictionary are appended to the list >>> alist+='MN' Displays [3, 'X', '4', 'M', 'N'] characters in the string are appended to the list FAIPS, DPS Kuwait Page 5 of 18 © Bikram Ally Python Notes Class XI List Replicate a list >>> list1=[24, 'TARUN', 56] >>> list2=3*list1 New list list2 is created by triplicating values stored in list list1. >>> print(list2) Displays [24, 'TARUN', 56, 24, 'TARUN', 56, 24, 'TARUN', 56] >>> list2=-3*list1 New list list2 is created which is empty. * >>> print(list2) Displays [] >>> list2=0*list1 New list list2 is created which is empty. >>> print(list2) Displays [] >>> list2=2.5*list1 Triggers are error. Updates an existing list by replicating values stored in the list >>> stu=[24, 'TARUN', 56] >>> stu*=2 The list stu is updated duplicating values stored in the list stu. >>> print(stu) Displays [24, 'TARUN', 56, 24, 'TARUN', 56] >>> stu*=-2 *= All the elements from list stu are deleted, the list becomes empty. >>> stu=[24, 'TARUN', 56] >>> stu*=0 All the elements from list stu are deleted, the list becomes empty. >>> stu=[24, 'TARUN', 56] >>> stu*=5.2 Triggers an error. Checks whether an element is present in a list >>> alist=[10, 20, 30, 40, 50] >>> print(30 in alist, 60 in alist) Displays True False in >>> stu=[24, 'TARUN', 56] >>> x='TARUN' in stu >>> y='RANJIT' in stu >>> print(x, y) Displays True False Deletes an element or elements from a list >>> marks=[24, 'TARUN', 'COMP SC', 56, 25] >>> del marks >>> print(marks) Displays [24, 'TARUN', 56, 25] Deletes the element whose index is 2 del >>> alist=[10,20,30,40,50] >>> del alist, alist >>> print(alist) Displays [10, 20, 50] since element whose is index 2 is deleted, so the list is left with 4 elements and next element from whose index 2 is deleted. >>> del alist Displays run-time error because index 5 is out of range. FAIPS, DPS Kuwait Page 6 of 18 © Bikram Ally Python Notes Class XI List Deletes a list >>> marks=[24, 'TARUN', 'COMP SC', 56, 25] del >>> del marks >>> print(marks) Displays run-time error because the list has been deleted from the memory. Checks whether two lists are equal >>> alist=[10, 20, 30] >>> blist=[10, 20, 30] >>> clist=[20, 10, 30] == >>> print(alist==blist) Displays True since corresponding elements of alist and blist are equal >>> print(alist==clist) Displays False since corresponding elements of alist and blist are not equal Two lists are compared by checking the values present in the corresponding elements. Checks whether two lists are not equal >>> alist=[10, 20, 30] >>> blist=[10, 20, 30] >>> clist=[20, 10, 30] != >>> print(alist!=blist) Displays False since corresponding elements of alist and blist are equal >>> print(alist!=clist) Displays True since corresponding elements of alist and blist are not equal Checks whether one list is greater than or equal to second list >>> alist=[10, 20, 30] >>> blist=[10, 20, 30] >>> clist=[20, 10, 30] >>> print(alist>blist) Displays False since corresponding elements of alist and blist are equal >>> print(alist>=blist) >,>= Displays True since corresponding elements of alist and blist are equal >>> print(alist>clist) Displays False since 10 of alist is less than 20 of clist >>> print(alist>=clist) Displays False since 10 of alist is less than 20 of clist If the two elements cannot be compared using > or >> a, b=[10, 'AB'], [10, 20] >>> print(a>b) Triggers an error. Checks whether one list is less than or equal to second list >>> alist=[10, 20, 30] >>> blist= [10, 20, 30] >>> clist=[20, 10, 30] >>> print(alist print(alist>> print(alist>> print(alist>> stu=eval(input('Input Roll, Name, Marks? ')) >>> Input Roll, Name, Marks? [23, 'Rupak', 79.5] Please remember, when inputting the values, start with [, inputted values are to be separated by comma (,), string type data to be enclosed within quotes ('/") and end with ]. >>> print(stu) Displays [23, 'Rupak', 79.5] >>> stu=eval(input('Input Roll, Name, Marks? ')) >>> Input Roll, Name, Marks? [23, Rupak, 79.5] Triggers a run-time error since RUPAK is inputted without quotes. print() As discussed earlier, function print() displays the entire list on the screen from left to right. >>> student=[24, 'TARUN', 'COMP SC', 56, 25] >>> print(student) Displays [24, 'TARUN', 'COMP SC', 59, 28] len() Function len() returns number of values (elements) present in a list. Function len() works with list of any type. >>> a=[55,45,25,65,15] >>> b=[2.5,6.7,9.3,5.7,1.2] >>> c=['DIPTI','AVEEK','SANDIP','NEETA','BHUVAN'] >>> d=[11.5,12,13.5,15,14.5,10] >>> e=[1001,'PRATAP JAIN','MANAGER','FINANCE', 250000.0] >>> print(len(a),len(b),len(c),len(d),len(e)) Displays 5 5 6 6 5 Function len() will return 0, if the list is empty. max(), min() Function max() returns the maximum value (highest / largest value) stored in the list. Function min() returns the minimum value (lowest / smallest value) stored in the list. Functions max() and min() can be used with list containing either homogeneous data type (either only int or only float or only str) or list containing only numbers (int type values and float type values). Using functions max() and min() with list containing int (float) type values and str type values will trigger run-time error. >>> a=[55,45,25,65,15] >>> b=[2.5,6.7,9.3,5.7,1.2] >>> c=['DIPTI','AVEEK','SANDIP','NEETA','BHUVAN'] >>> d=[11.5,12,13.5,15,14.5,10] >>> e=[1001,'PRATAP JAIN','MANAGER','FINANCE', 250000.0] >>> print(max(a),max(b),max(c),max(d)) Displays 65 9.3 SANDIP 30 >>> print(min(a),min(b),min(c),min(d)) Displays 15 1.2 AVEEK 1.5 >>> print(max(e)) Displays run-time error since type str and type int(float) type and cannot be compared using either > or < operator. >>> print(min(e)) Displays run-time error since type str and type int(float) type and cannot be compared using either > or < operator. FAIPS, DPS Kuwait Page 8 of 18 © Bikram Ally Python Notes Class XI List sum() Function sum() returns the sum of the elements stored in the list, provided list contains only numbers (all int type or all float type or only numbers). If a list contains str type value or list contains numbers and strings, function sum() triggers a run-time error. >>> a=[55,45,25,65,15] >>> b=[2.5,6.7,9.3,5.7,1.2] >>> c=['DIPTI','AVEEK','SANDIP','NEETA','BHUVAN'] >>> d=[11.5,12,13.5,15,14.5,10] >>> e=[1001,'PRATAP JAIN','MANAGER','FINANCE', 250000.0] >>> print(sum(a)) Displays 205 (55+5+25+65+15) >>> print(sum(b)) Displays 25.4 (2.5+6.7+9.3+5.7+1.2) >>> print(sum(d)) Displays 76.5 (11.5+12+13.5+15+14.5+10) >>> print(sum(c)) Displays run-time error since string type cannot be added to obtain a sum. >>> print(sum(e)) Displays run-time error since integer type and string type cannot be added. sorted() Function sorted() returns a list sorted in ascending order by default but it does not sort the list. Function sorted()can be used with list containing either homogeneous data type (either only int or only float or only str) or list containing only numbers (int type values and float type values). By default function sorted() will return a list sorted in ascending order. By using reverse=True, will return a list sorted in descending order. If a list contains int (float) type values and str type values, using functions sorted() will trigger run-time error. >>> a=[55,45,25,65,15] >>> b=[2.5,6.7,9.3,5.7,1.2] >>> c=['DIPTI','AVEEK','SANDIP','NEETA','BHUVAN'] >>> d=[11.5,12,13.5,15,14.5,10] >>> e=[1001,'PRATAP JAIN','MANAGER','FINANCE', 250000.0] >>> print(sorted(a)) Displays [15, 25, 45, 55, 65] >>> print(a) Displays [55,45,25,65,15], the unsorted list (does not sort the list) >>> print(sorted(b)) Displays [1.2, 2.5, 5.7, 6.7, 9.3] >>> print(sorted(c)) Displays ['AVEEK', 'BHUVAN', 'DIPTI', 'NEETA', 'SANDIP'] >>> print(sorted(d)) Displays [10, 11.5, 12, 13.5, 14.5, 15] >>> print(sorted(a, reverse=True)) Displays [65, 55, 45, 25, 15] >>> print(sorted(b, reverse=True)) Displays [9.3, 6.7, 5.7, 2.5, 1.2] >>> print(sorted(c, reverse=True)) Displays ['SANDIP', 'NEETA', 'DIPTI', 'BHUVAN', 'AVEEK'] >>> print(sorted(e)) Triggers run-time error since list containing str type and int(float) type and cannot be compared using either > or < operator. FAIPS, DPS Kuwait Page 9 of 18 © Bikram Ally Python Notes Class XI List Functions from list class (methods of list class) Appends an element in a list >>> alist=[10,20,30,40] >>> alist.append(50) Appends 50 to the list (50 is added at the end, after 40). >>> print(alist) Displays [10, 20, 30, 40, 50] append() >>> alist.append([60,70]) Appends [60, 70] to the list. >>> print(alist) Displays [10, 20, 30, 40, 50, [60,70]] >>> alist.append(80,90) Triggers run-time error because append() needs one argument but two are given. Values (elements(present) in am iterable is appended to a list >>> alist=[10,20,30,40] extend() >>> alist.extend(iterable) is exactly same as alist+=ierable Please refer to += operator discussed earlier. Creates a new list which the duplicate of an existing list which is not an alias >>> list1=[10,20,30,40] >>> list2=list1.copy() As discussed earlier, = (assignment operator creates an alias) but copy() method creates a new list list2 is created which the duplicate of an existing list list1. The two lists copy() list1 and list2 are allocated two different memory location. Any change in the list1 will not update list2 and vice versa. >>> list1+= #does not update list2 >>> list2+= #does not update list1 >>> print(list1, list2) Displays [10, 20, 30, 40, 50] [10, 20, 30, 40, 60] Removes (deletes) all the elements from a list but the list is not deleted >>> alist=[10,20,30,40] >>> alist.clear() clear() All the elements are removed (deleted) from the list. >>> print(alist, len(alist)) Display [] 0 #Empty list => len(alist) is 0 (zero) Returns count of a value (an element) present in the list >>> alist=[10,20,30,40,10,20,30,10,20,20] >>> print(alist.count(20)) count() Displays 4, because 20 appears 4 times in the list. >>> print(alist.count(40), alist.count(70)) Displays 1 0, because 10 appears in the list only once and 70 is not in the list. Returns the lowest positive index of a value (an element) that is present in the list >>> alist=[10,20,30,40,10,20,30,10,20,20] >>> print(alist.index(20)) Above statement means look for 20 from the beginning. Displays 1, because the lowest index of 20 from the left is 1. >>> print(alist.index(40)) index() Displays 3, because the lowest index of 40 from the left is 3. >>> print(alist.index(20,4)) Above statement means look for 20 starting from the 4th index. Displays 5, because the lowest index of 20 staring from 4th index is 5. >>> print(alist.index(20,6,9)) Above statement means, look for 20 starting from the 6th index, till 8th index. FAIPS, DPS Kuwait Page 10 of 18 © Bikram Ally Python Notes Class XI List Displays 8, because the lowest index of 20 staring from 6th index is 6. >>> print(alist.index(100)) Triggers run-time error because 100 is not in the list. >>> print(alist.index(40,6,9)) Triggers run-time error because 40 is not in the list within that range (6th to 8th). Inserts a value (an element) into a list >>> alist=[10,30,50,70] >>> alist.insert(1,20) Inserts 20 at the index 1 and elements from index 1 are shifted one index to the right. >>> print(alist) Display [10, 20, 30, 50, 70] >>> alist.insert(10,60) insert() 60 is appended in the list even when index 10 is out of range. >>> print(alist) Display [10, 20, 30, 50, 70, 60] >>> alist.insert(0,[11,22]) Inserts [11,22] at the index 0, elements from index 0 are shifted one index to the right. >>> print(alist) Display [[11, 22], 10, 20, 30, 50, 70, 60] Deletes an element from a list for a given index >>> alist=[10,20,30,40,70] >>> alist.pop() Function pop() without any parameter deletes the last element from the list. In the IDLE shell, the above statement will display 70, but in the script mode, nothing will be displayed. >>> x=alist.pop(1) Deletes 20 and 20 is stored in the variable x. >>> print(x) pop() Displays 20. >>> print(alist) Displays [10, 20, 30, 40, 50] >>> alist.pop(2) #Same as del alist Function pop()with parameter deletes alist from the list. >>> print(alist) Displays [10, 20, 30, 40] >>> alist.pop(10) Triggers run-time error because index 10 is out of range. Deletes the first occurrence of an element, starting from left, if present in a list >>> alist=[10,20,30,40,20] >>> alist.remove(30) Deletes 30 from the list. >>> print(alist) Displays [10, 20, 40, 20] >>> alist.remove(20) Deletes the first occurrence of 20 (from left) from the list. remove() >>> print(alist) Displays [10, 40, 20] >>> alist.remove(alist) Deletes alist from the list. >>> print(alist) Displays [10, 20] >>> alist.remove(100) Triggers run-time error because 100 is not in the list. FAIPS, DPS Kuwait Page 11 of 18 © Bikram Ally Python Notes Class XI List Reverses the elements in a list >>> alist=[10,20,30,40,50] >>> alist.reverse() reverse() Reverses the elements in the list permanently. >>> print(alist) Displays [50, 40, 30, 20, 10] Elements of the list are re-arranged in the opposite order. Sorts a list (elements in a list are re-arranged by default in ascending order) Built-in function sorted() returns a sorted list, but does not sort the list. Method sort() will sort the list. Function sort()can be used with list containing either numbers (int type values and float type values) or strings. If a list contains numbers and strings, using functions sort() will trigger run-time error. >>> alist=[50, 20, 40, 10, 30] >>> alist.sort() >>> print(alist) Displays sorted alist in ascending order as [10, 20, 30, 40, 50] sort() >>> alist=[50, 20, 40, 10, 30] >>> alist.sort(reverse=True) >>> print(alist) Displays sorted alist in descending order as [50, 40, 30, 20, 10] >>> alist=[66, 22.4, 44, 55.7, 11, 33.9] >>> alist.sort() >>> print(alist) Displays sorted alist in ascending order as [11, 22.4, 33.9, 44, 55.7, 66] >>> alist=[24, 'TARUN', 'COMP SC', 56.5, 25] >>> alist.sort() Triggers run-time error because list containing numbers and strings cannot be sorted. How to store values in a list by inputting values from the keyboard during the run-time: List containing homogeneous values #Program01 - list of int Variable alist is an empty list. Statement alist=[] #alist=list() alist+=[num] n=int(input('No. of elements? ')) OR, alist.append(num) for k in range(n): will append value stored in the variable num to num=int(input('Integer? ')) the list. Since the variable num is an integer type, alist+=[num] all the elements in the list will be of the type #alist.append(num) integer. print(alist) List containing homogeneous values #Program02 - list of float Variable alist is an empty list. Statement alist=[] #alist=list() alist+=[num] n=int(input('No. of elements? ')) OR, alist.append(num) for k in range(n): will append value stored in the variable num to num=float(input('Value? ')) the list. Since the variable num is a float type, all alist+=[num] the elements in the list will be of the type float. #alist.append(num) print(alist) Variable alist is an empty list. Statement List containing homogeneous values #Program03 - list of str alist+=[astr] alist=[] #alist=list() OR, alist.append(astr) n=int(input('No. of elements? ')) will append value stored in the variable astr to for k in range(n): the list. Since the variable astr is a str type, all astr=input('String? ') the elements in the list will be of the type str. FAIPS, DPS Kuwait Page 12 of 18 © Bikram Ally Python Notes Class XI List alist+=[astr] #alist.append(astr) print(alist) List containing heterogeneous values #Program01 - list of numbers Variable alist is an empty list. Statement alist=[] #alist=list() num=eval(input('Number? ')) n=int(input('No. of elements? ')) Variable num will be int (float) if an integer for k in range(n): (floating-point) value is inputted. Statement num=eval(input('Number? ')) alist+=[num] #list.append(num) alist+=[num] will append value stored in the variable num to #alist.append(num) the list. So, values in the list will be either an int print(alist) or a float. List containing heterogeneous values #Program02 - list containing int, str and float rn=int(input('Roll? ')) na=input('Name? ') th=float(input('Theo? ')) Using loop one can input / store homogeneous pr=float(input('Prac? ')) values in a list. To create a list of heterogenous gr=input('Grade? ') values, values are to be inputted. Values are alist=[rn, na, th, pr, gr] inputted in rn, na, th, pr, and gr. A list print(alist) alist is created with rn, na, th, pr and gr. OR, A list containing int, float and str can only alist= [ be created by inputting values from the keyboard int(input('Roll? ')), during the run-time. input('Name? '), float(input('Theo? ')), float(input('Prac? ')), input('Grade? ') ] print(alist) How to store values in a list by using methods from random module: List containing homogeneous values Variable alist is an empty list. Function #Program01 - list of int randint(10,99) generates 2-digit from random import * random integers. Statement n=int(input('Input n? ')) alist+=[randint(10,99)] alist=[] #alist=list() appends an element in the list. Instead one can for k in range(n): use following code to create a list with n alist+=[randint(10,99)] random integer values: #alist+=[randrange(10,100)] alist=[randint(10,99) for x in #alist.append(randrange(10,100)) range(n)] ''' alist=[randint(10,99) for x in range(n)] #alist=[randint(10,100) for x in range(n)] ''' print(alist) Variable alist is an empty list. Function randint(10,99) generates a floating point value List containing homogeneous values #Program02 - list of float between 10 and 99. Statement from random import uniform alist+=[uniform(10,99)] n=int(input('Input n? ')) appends an element in the list. Instead one can use alist=[] #alist=list() following code to create a list with n random floating- for k in range(n): point values: num=uniform(10,99) alist=[uniform(10,99) for x in alist+=[num] range(n)] FAIPS, DPS Kuwait Page 13 of 18 © Bikram Ally Python Notes Class XI List #alist.append(num) ''' alist=[uniform(10,99) for x in range(n)] ''' print(alist) List containing homogeneous values Variable alist is an empty list. Statement #Program03 - list of str astr=chr(6*randint(65,90)) from random import randint creates a string with 6 letters (same letters). Practically n=int(input('Input n? ')) this kind of code will be of no use. Statement alist=[] #alist=list() alist+=[astr] for k in range(n): appends a string astr in the list. Instead one can use astr=chr(6*randint(65,90)) following code to create a list with n random strings: alist+=[astr] alist=[6*chr(randint(65,90)) for x in #alist.append(astr) range(n)] ''' alist=[6*chr(randint(65,90)) for x in range(n)] ''' print(alist) Creating list and displaying list using a loop #Program04 from random import randint n=int(input('No. of elements? ')) alist=[randint(10,99) for k in range(n)] for k in range(n): print(alist[k]) A list can be displayed using a loop ''' Using a for / while loop to generate the index of the OR, elements and then displaying the elements using list k=0 variable name and the index. Between for loop and while k0: s+=ele c+=1 print(ele, end=' ') ''' avg=s/c print('\nNumber of Elements not divisible by 5=',c) print('Sum of Elements not divisible by 5=',s) print('Avg of Elements not divisible by 5=',avg) Processing a list #Program10 – find max and min stored in a list from random import uniform n=int(input('No. of elements? ')) alist=[round(uniform(10,99),2) for k in range(n)] hi=lo=alist for k in range(1, n): if hi>alist[k]: hi=alist[k] elif loalist[k]: hi=alist[k] ph=k elif lo0: s1+=alist[k] else s2+=alist[k] print(alist[k], end=' ') ''' k=0 while k0: s1+=alist[k] else s2+=alist[k] print(alist[k], end=' ') k+=1 ''' print('\nSum of elements at odd index=',s1) print('Sum of elements at even index=',s2) Linear search Sequentially a value is searched in a list starting form the first element (starting from left or stating from index 0). Either the value is in the list or the value is not in the list. If value is located in the list, there is no need to search any more. from random import randint n=int(input('No. of elements? ')) alist=[randint(10,99) for k in range(n)] print(alist) item=int(input('Item to search? ')) FAIPS, DPS Kuwait Page 17 of 18 © Bikram Ally Python Notes Class XI List found=0 Search item (item) is compared for k in range(n): if item==alist[k]: with every element in the list. If the found=1 search item is found in the list, flag break variable found is updated to 1 and if found: the while loop terminates. If the print(item, 'found in the list') search item is not in the list, the while else: loop terminates when k==n (end of print(item, 'not found in the list') the list). Value stored in the flag ''' variable found is tested after the found=k=0 while loop. while k>> print(str1) Displays the string str1 as MANGO. Kindly note, when a string displayed, the delimiters are not displayed. How to access a character in a string? To access a character in a string we need to do the following: strname[index] Data type for index must be an int. If a string has n characters then indices are: 0, 1, 2, …, n-3, n-2, n-1 Non-negative index -n, -(n-1), -(n-2), …, -3, -2, -1 Negative index If index is out of range (access a character with an invalid index), will trigger a run-time error. >>> str1='MNAGO' >>> for k in range(5): print(str1[k],end=' ') Displays the string left to right: M A N G O >>> for k in range(1,5): print(str1[-k],end=' ') Displays the string right to left: O G N A M >>> for ch in str1: print(ch,end=' ') Displays the string left to right: M A N G O FAIPS, DPS Kuwait Page 1 of 10 © Bikram Ally Python Notes Class XI String >>> print(str1) >>> print(str1[-6]) Displays run-time error: string index out of range since a string has only 5 characters. Using operators and keyword del with type Creates a new string but cannot update a value stored in the string >>> str1, str2='India, New Delhi', 'SONDAY' >>> print(str1) = Displays India, New Delhi >>> str1='U' Displays run-time error because the string is an immutable type. Concatenate two or more strings >>> str1='India,'+' New'+' Delhi' + >>> print(str1) Displays India, New Delhi Updates an existing string by concatenating another string >>> str1='New' >>> print(str1, id(str1)) += Displays New, 2273046316016 >>> str1+=' Delhi' >>> print(str1, id(str1)) Displays New Delhi 2273041112864 since string is an immutable type, ID changes Replicate a string >>> str1='Kuwait' >>> print(str1*3) Displays KuwaitKuwaitKuwait >>> print(str1*0) * Displays an empty string >>> print(str1*-3) Displays an empty string >>> print(str1*2.5) Triggers an error A string can be multiplied with an integer value. Updates an existing string by replicating values stored in the string >>> str1='Delhi' >>> str1*=3 *= The string str1 is updated triplicating values stored in the string. >>> print(str1) Displays DelhiDelhiDelhi Deletes a string >>> str1='Mangaf' >>> del str1 >>> print(str1) del Displays run-time error because the string str1 has been deleted from the memory. >>> str1='Mangaf' >>> del str1 Displays run-time error because the string is an immutable type. Check whether a sub-string is a member of tuple >>> str1='MANGAF' >>> print('MAN' in str1, 'G' in str1) in Displays True True since 'ANG' and 'G' are present in the string str1 >>> print('GN' in str1) Displays False since 'GN' is present in the string str1 FAIPS, DPS Kuwait Page 2 of 10 © Bikram Ally Python Notes Class XI String Built-in functions for string data type print() As discussed earlier, function print() displays string on the screen without the delimiters. len() Function len() returns number of characters present in a string. >>> str1,str2='FAIPS-DPS',"" >>> print(len(str1), len(str2)) Display 9 0 max(), min() Function max() returns the character with highest ASCII code / Unicode from a string. Function min() returns the character with lowest ASCII Code (Unicode) from a string. >>> str1='FAIPS' >>> print(max(str1), min(str1)) Display S A sorted() Function sorted() returns a list containing characters present in the string sorted in ascending order but does not sort the characters present in the string. Using reverse=True returns a list sorted in descending order. >>> str1='FAIPS' >>> sorted(str1) Displays ['A', 'I', 'F', 'P', 'S'] >>> sorted(str1, reverse=True) Displays ['S', 'P', 'I', 'F', 'A'] >>> print(str1) Displays FAIPS Methods from string objects: Function name Use of the function of the function Returns a string converted to uppercase. Only lowercase is converted to uppercase. address='GH-14/783,Paschim Vihar,New Delhi-110087' upper() print(address.upper()) Displays GH-14/783,PASCHIM VIHAR,NEW DELHI-110087 Returns a string converted to lowercase. Only uppercase is converted to lowercase. address='GH-14/783,Paschim Vihar,New Delhi-110087' lower(), print(address.lower()) casefold() Displays gh-14/783,paschim vihar,new delhi-110087 print(address.casefold()) Displays gh-14/783,paschim vihar,new delhi-110087 Checks whether the string contains uppercase. Returns True if str does not contains any lowercase. Returns False if a string contains lowercase. isupper() a,b,c='FAIPS', 'FaIpS', 'PO BOX-9951' print(a.isupper(), b.isupper(), c.isupper()) Displays True False True Checks whether the string contains lowercase. Returns True if str does not contains any uppercase. Returns False if a string contains uppercase. islower() a,b,c='faips', 'fAiPs', 'po box-9951' print(a.islower(), b.islower(), c.islower()) Displays True False True Checks whether the string contains only alphabets (uppercase and lowercase). Returns True isalpha() if a string contains either uppercase or lowercase or both. Returns False if a string does not contain any digits or any special characters. a,b,c,d='DPS','dps','DpS','PO Box-9951' FAIPS, DPS Kuwait Page 3 of 10 © Bikram Ally Python Notes Class XI String print(a.isalpha(),b.isalpha(),c.isalpha(),d.isalpha()) Displays True True True False Checks whether the string contains digit. Returns True if a string contains only digit. Return False if a string contains either alphabets or special characters or both. isdigit() a,b,c,d='1234','FLAT24','flat24','Flat-24' print(a.isdigit(),b.isdigit(),a.isdigit(),d.isdigit()) Displays True False False False Checks whether the string contains either alphabet or digit or both. Returns True if a string contains either alphabet or digit or both. Return False if a string contains special characters. isalnum() a,b,c,d='Flat24','FLAT24','flat24','Flat-24' print(a.isdigit(),b.isdigit(),a.isdigit(),d.isdigit()) Displays True True True False Checks for whitespace characters space(' '), tab('\t') or new line('\n') present in a string. A whitespace character is not visible on the screen. Returns True if a isspace() string contains only whitespace character(s). a,b,c,d=' ',' \t',' \t \n', 'New - Delhi' print(a.isspace(),b.isspace(),a.isspace(),d.isspace()) Displays True True True False Returns a string by converts the first character of a string to uppercase and rest of the alphabetic characters are converted to lowercase. str1,str2,str3='NEW DELHI','new delhi','NeW dElHi' print(str1.capitalize(), str2.capitalize(), end=' ') capitalize() print(str3.capitalize()) Displays New delhi New delhi New delhi >>> city='*NEW*delhi' >>> print(city.capitalize()) Displays *new*delhi Return a string by converting first character of every word (sub string separated by white- space character(s)) present in a string converted to uppercase, rest of the alphabetic characters in the word will be converted to lowercase. str1,str2,str3='NEW DELHI','new delhi','NeW dElHi' title() print(str1.title(),str2.title(), str3.title()) Displays New Delhi New Delhi New Delhi >>> city='*NEW*delhi' >>> print(city.title()) Displays *New*Delhi Exactly same as count() method of list and it returns occurrence of a sub-string present within big string. Returns 0 if the sub-string could not be located within the big string. s='NEW DELHI' count() print(s.count('E'),s.count('DEL'),s.count('IN')) Displays 2 1 0 print(s.count('E',4),s.count('W',4,9)) Displays 1 0 Almost similar to index() method list and it returns lowest non-negative index of a sub- string present within another string. Unlike index() method of list, it returns -1 when the sub-string could not be located in the string. s='NEW DELHI' print(s.find('E'),s.find('DEL'),s.find('IN')) find() Displays 1 4 -1 print(s.find('E',4),s.find('E',6)) Displays 5 -1 print(s.find('E'),s.find('E',4),s.find('E',6,10)) Displays 1 5 -1 FAIPS, DPS Kuwait Page 4 of 10 © Bikram Ally Python Notes Class XI String Exactly similar to index() method list and it returns lowest non-negative index of a sub- string present within a big string. If a sub-string is not present within the big string, it will trigger a run-time error. s='NEW DELHI' print(s.index('E'),s.index('DEL'),s.index('E',4)) index() Displays 1 4 5 print(s.index('D',2,7)) Displays 4 print(s.index('Z')) Triggers a run-time error Removes all the white-space characters from the both ends of a string. s=' Mangaf, Kuwait ' strip() print(s.strip()) Displays Mangaf, Kuwait removing white space characters from both ends Removes all the white-space characters from the left (beginning) of a string. s=' Mangaf, Kuwait ' lstrip() print(s.strip()) Displays Mangaf, Kuwait removing white space characters from left Removes all the white-space characters from the right (end) of a string. s=' Mangaf, Kuwait ' rstrip() print(s.strip()) Displays Mangaf, Kuwait removing white space characters from right Creates a list containing sub-string from a big string separated by white space character(s) by default or separated by a delimiter. Delimiter is not included in the list. s='Sun Mon Tue Wed Thu Fri Sat' wlist=s.split() print(wlist) Displays ['Sun', 'Mon', 'Tue', 'Wed', 'Thu'] since parameter is missing from split() method, the default delimiter is white-space s='Sun,Mon,Tue,Wed,Thu' split() print(s.split(',')) Displays ['Sun', 'Mon', 'Tue', 'Wed', 'Thu'] print(s.split(',',3)) Displays ['Sun', 'Mon', 'Tue', 'Wed,Thu'] s='FAIPS,DPS,Kuwait' print(s.split('*')) Displays ['FAIPS,DPS,Kuwait'] since delimited '*' is missing, list contains only one element, the entire string The partition() method searches for a specified sub-string, and splits the big string into a tuple containing three elements. The first element contains the part before the specified string. The second element contains the specified string. The third element contains the part after the string. s='MangafFahaheelAhmadi' alist=s.partition('Fahaheel') print(alist) Displays ('Mangaf', 'Fahaheel', 'Ahmadi') partition() alist=s.partition('Mangaf') print(alist) Displays ('', ' MangafFahaheel', 'Ahmadi') Print(s.partition('Ahmadi')) Displays ('MangafFahaheel', 'Ahmadi', '') alist=s.partition('Delhi') print(alist) Displays ('MangafFahaheelAhmadi', '', '') FAIPS, DPS Kuwait Page 5 of 10 © Bikram Ally Python Notes Class XI String The join() method takes all items (all items must be string) from an iterable (list / tuple / dictionary) and joins them into one string. A string must be specified as the separator. alist=['10','ASHOK','89.0'] blist=('21','ROOPA','75.5') join() astr=','.join(alist) #',' is the separator bstr='~'.join(blist) #'~' is the separator print(astr, bstr) Displays 10,ASHOK,89.0 21~ROOPA~75.5 The replace() method replaces a specified phrase with another specified phrase. s='ABCD , 1234 , efgh , {()}' t=s.replace(' , ', '') replace() print(t) Displays ABCD1234efgh{()} By default replaces all occurrence of ' , ' with '' The startswith() method returns True if the string starts with the specified value, otherwise False. s='Hello, Python' startswith() print(s.startswith('Hell'), s.startswith('Python')) Displays True False print(s.startswith('Python', 7)) Displays True The endswith() method returns True if the string ends with the specified value, otherwise False. s='Hello, Python' endswith() print(s.endswith('Hell'), s.endswith('Python')) Displays False True print(s.endswith('Hell',0)) Displays True sorted() sort() It is a built-in function It is a list method Returns a list Returns None Does not sort a list / tuple / string / dictionary Sorts a list physically, by default elements are physically sorted in ascending order Accepts list / tuple / string / dictionary (iterable) as Does not accept tuple / string / dictionary (any a parameter iterable) as a parameter List Tuple A list is delimited by [] A tuple is delimited by () For a list, delimiter [] is mandatory For a tuple, delimiter () is optional A list type data is mutable A tuple type data is immutable An element of a list can be updated using = An element of a tuple cannot be updated using = An element of a list can be deleted with del An element of a tuple cannot be deleted with del A list pass by reference to a function A tuple is pass by value to a function Mutable Immutable Can be updated Cannot be updated = operator creates an alias = operator creates a copy Since it can be updated, by updating a mutable type, Since it cannot be updated, updating a mutable type no new object is created will create a new object Since it can be updated, no new id is allocated Since it cannot be updated, new id is allocated Passed as a reference parameter to a function Passed as a value parameter to a function Data type Features FAIPS, DPS Kuwait Page 6 of 10 © Bikram Ally Python Notes Class XI String List Mutable type, collection, sequence, iterable type, built-in type Tuple Immutable type, collection, sequence, iterable type, built-in type String Immutable type, sequence, iterable type, fundamental type Dictionary Mutable type, collection, mapping, iterable type, built-in type #Obtain a new string by converting an inputted string into uppercase astr=input('Input a string? ') bstr='' for ch in astr: if 'a'