We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7
Chapter: LISTS Here B will be created with the help of A and its each
In Python, a list is a sequence of mutable (modifiable) element will be thrice of element of A.
heterogeneous (mixed arbitrary data types) items print(B) enclosed in a square bracket ([ ]) where the entire [9, 12, 15] sequence is referred to by a single name and individual Comprehensions are functionally equivalent to writing items can be selected by indexing (either 0 to size-1 or -1 as: to -size). In a nutshell, Python lists are mutable A = [3, 4, 5] sequences of arbitrary objects. B=[] Virtually all computer languages provide some sort of for i in A: sequence structure similar to Python's list; in other B. append (i*3) languages, it is called an array which holds print(B) homogeneous elements and it is static. Whereas, Python [9, 12, 15] lists are dynamic i.e. they can grow and shrink on ➢ Using built-in object demand. L = list ( ) #will create an empty list For ex. OR [12,34.56,’Tiranga’,909,45.56] L = list (sequence) [12,34,23,43] Example: [‘Ajay’, ‘Gandharv’,’Animesh’] L = list ([1, 2, 3, 4]) print(L) Creating lists: [1, 2, 3, 4] List can be created in many ways: A single new list is created every time, you execute [ ]. ➢ By enclosing elements in [ ] But if a list is assigned to another variable, a new list is Variable_name=[val1,val2,val3,……..] not created. Some example of simple list: i) A=B=[ ] i) L1 = [1, 2, 3, 4] # list of 4 integer elements. Creates one list mapped to both A & B ii) L2 = [“Delhi”, “Chennai”, “Mumbai”] #list of 3 Example: string elements. >>>A = B = [10, 20, 30] iii) L4 = [“abc”, 10, 20] # list with different types of >>> print(A, B) elements [10, 20, 30] [10, 20, 30] iv) L5 = [1, 2, [6, 7, 8], 3] ii) A = [ ] # A list containing another list known as nested list B=A We will study about Nested lists in later parts of the Will also create one list mapped to both chapter. Example: v) A=[] #empty list >>> A = [1, 2, 3] ➢ Using other Lists >>> B = A Examples: >>> print( A, B) 1) L1=[1,2,3] [1, 2, 3] [1, 2, 3] L5=L1 #L5 created from other list L1 2) L4=L1[:] #another way to create from other list STORAGE STRUCTURE & ACCESSING OF 3) By slicing from an existing list PYTHON LISTS: L=[2,4,6,8,10] In Python, Lists are sequences just like strings. They L2=L[1:4] #will create L2 list with elements from index also index their individual elements just like strings do. 1 to 4-1 List actually stores element’s memory address in print(L2) sequence not the element itself. It can be understood by [4, 6, 8] the following image: ➢ Using List comprehension Examples: 1) S= [x**2 for x in range (10)] print (S) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] In mathematical terms, S can be defined as S = {x2 for: x in (0.....9)}. So, we can say that list comprehension is short-hand for creating list. A list also manages two ways indexing for each location. 2) A = [3, 4, 5] It can be understood by the following table for list B = [value *3 for value in A] L=[15,56,78,34,90]: Forward indexing for i in [ ]: 0 1 2 3 4 print(i,end=’ ‘) 15 56 78 34 90 Accessing list with negative index -5 -4 -3 -2 -1 Backward indexing L1=[1,2,5,4] An individual value in a list is accessed using a subscript i=1 (index). The subscript should always be an integer while i <= len (L1): (positive or negative). In Python, a subscript always print(L1 [-i],end=’ ‘) starts from either 0 or -length. i += 1 For example: Above code will print the list in reverse order: >>> L=[15,56,78,34,90] 4521 >>> print(L[0]) 15 L1=[1,2,5,4] >>> print(L[-1]) i=4 90 while i>0: >>> print(L[2]) print(L1 [-i],end=’ ‘) 78 i -= 1 >>> print(L[-3]) Above code will print the list as follows: 78 1254 Note: Since lists are mutable, it is often recommended to make a copy of it before performing operation that Q. Write a program to display the sum of 5 numbers change a list. present in a list. L=[2,4,5,3,6] Traversing a List: It means visiting each and every i=0 element of List individually for printing or sum=0 modification, if necessary. This can be done in many while i<5: ways: Examples are: sum+=L[i] i) i+=1 L1=[1,2,5,4] print('Sum of all numbers = ',sum) i=0 OR while i <4: L=[2,4,5,3,6] print(L1 [i],end=’ ‘) sum=0 i+=1 for i in range(5): will produce following output sum+=L[i] 1254 print('Sum of all numbers = ',sum) ii) L1=[1,2,5,4] OR for i in L1: L=[2,4,5,3,6] print(i,end=’ ‘) sum=0 for i in L: iii) L1=[1,2,5,4] sum+=i i=0 print('Sum of all numbers = ',sum) while i < len (L1): print(L1 [i],end=’ ‘) Appending Elements in the list: i+=1 Appending a list means adding more element(s) at the OR end of the list. The append( ) adds only one element at L1=[1,2,5,4] the end of an existing list. Its Syntax is: i= 0 ListName.append (DataItem) L = len (L1) For example: while i < L : L1=[11,21,34,51] print(L1[i],end=’ ‘) L1. append (70) i+=1 This will add 70 to the list at the end, so now 70 will be iv) the 5th element of the list, as it already have 4 elements. L1=[1,2,5,4] >>> print(L1) for i in range ( len (L1)): will produce following on screen: print(L1 [i],end=’ ‘) [11, 21, 34, 51, 70] Note: for loop in empty list is never executed: Example The append() function does not return the new list, just Example 2: modifies the original list. It can be understood as >>>A=[10, 20, 30, 40] follows: >>>A [1:4] = [100] >>> L=[10,20,30] >>>print(A) >>> L2=L.append(40) will produce >>> L2 #prints empty [10, 100] >>> L It happens because only one value is being assigned for [10, 20, 30, 40] ranges 1,2 & 3, as a result only index 1 is updated & If we try to append more than one element with append() rest other(2 & 3) index elements of the list are function, it reports ‘Syntax Error’, but if we try to removed. append multiple elements in the form of a list, it adds Example 3: that list as one element in the list i.e. original list >>>l=[10,20,30,40] becomes a nested list. For example: >>> l[1:3]=[100] >>> L=[10, 20, 30, 40] >>> l >>> L.append([50,60]) Will produce >>> L [10, 100, 40] [10, 20, 30, 40, [50, 60]] INPUT VALUES IN LIST BY USING eval( ) function: Q. Write a program to input five numbers in a list, We use eval(input()) to input a list during run time as calculate & display the sum of all the numbers. well. It is done as follows: Sol.: >>> L=eval(input("Enter a list:")) L=[] Enter a list:[2,4,6,8] print('Enter 5 numbers in the list:-') >>> L for a in range(5): [2, 4, 6, 8] val=float(input()) OR L.append(val) >>> L=eval(input("Enter a list:")) tot=0 Enter a list:['Madhur',34,'Gayab Singh'] for i in L: >>> L tot+=i ['Madhur', 34, 'Gayab Singh'] print('Sum of all values in list=',tot) Q. WAP to find out the sum of all even numbers Updating list elements: Updating an element of list is, present in a list having N numbers accomplished by accessing the element & modifying its SOL. value in place. It is possible to modify a single element Q. WAP to find out and print the total and average of or a part of list. To update single element, we use index all the numbers present in a list holding N numbers to access single element and for updating part of list, list which are divisible by 3. slice is used. Example: to update single element 12 5 18 9 25 99 A=[10,44,56,23,89] 0 1 2 3 4 5 A[3]=46 Q. WAP to increase all even numbers by 150% A[-4]+=10 present in a list having N numbers print(A) Q. WAP to find out the greatest number present in a [10, 54, 56, 46, 89] List having N numbers Example: to update part of the list Q. WAP to reverse all the data elements present in a Example 1: list of size N. A=[10, 44, 56, 46, 89] For ex. : If the list is- A[21,54,676,34,78], then it A [1:2] = [10, 20] should become: print(A) A[78,34,676,54,21] [10, 10, 20, 56, 46, 89] Q. WAP to arrange the list of even size as follows: It will happen because we tried to update one element of if a list is [12,23,11,45,56,23] list i.e. index 1:2-1=1 by providing 2 values 10 & 20 it should be arranged as: respectively. If we could have given: [23,12,45,11, 23, 56] A=[10,54,56,46,89] Q. WAP to arrange elements present in a list having A[1:3]=[10,20] N numbers as follows: print(A) if a list is [12,23,11,45,78,90] would have printed: it should be arranged as: [10, 10, 20, 46, 89] [90,12,23,11,45,78] Q. WAP to combine the contents of two equi-sized list A & B by adding their corresponding elements as the Replicating lists (*): The replication operator is used to formula A[i]+B[i], where value I varies from 0 to replicate a list specified number of times. Example 1: size-1 and transfer the resultant content in the third L1=[1,2,3] list C. B = L1*2 List A print(B) 4 6 9 2 [1,2,3,1,2,3] List B Example 2: 3 4 2 6 >>> [“Hi!”]* 3 List C [“Hi!”, “Hi!”, “Hi!”] 7 10 11 8 If we want to concatenate a list and string, either we Q. WAP to modify the content of the list in such a have to convert the list to string or string to list. way that the elements , which are multiples of 10, Examples: swap with the value present in the very next position >>> str([11,12])+"34" of the List having N numbers. '[11, 12]34' For ex.: >>> "[11,12]"+"34" If the content of the list is: [91,50,54,22,30,59] '[11,12]34' The content of the list should become: >>> [11,12]+list("34") [91,54,50,22,59,30] [11, 12, '3', '4'] Q. WAP to search the given integer present in a list holding N integers Slicing the lists: Just like strings we can slice an Q. WAP to create elements of list B[] with the help of existing list by using the valid list indexes as per the corresponding elements of list A[] i.e. if A[i] is +ve, following syntax: B[i] should be 1, and if A[i] is –ve, B[i] should be -1, Seq=List[start:Stop[:step]] and if A[i] is zero, B[i] should also be 0. For example: Example 1: If list A contains: >>> L=[12,34,45, 67,89] [-98, 56, 0, -23, -34, 54] >>> L1=L[1:3] The contents of list B should become: >>> print(L1) [-1, 1, 0, -1, -1, 1] [34, 45] Q. Write a program in Python, which accepts a list Example 2: Arr of numbers and n is a numeric index value by >>> L=[10,20,30,40] which all elements of the list are shifted to left. >>> L1=L[-2:-1] Sample Input Data of the list : >>> L1 Arr= [ 10,20,30,40,12,11], n=2 [30] Output : Example 3: Arr = [30,40,12,11,10,20] >>> L=[12,34,45, 67,89] Sol. >>> L1=L[1:10] Q. Write a program in Python, which accepts a list L >>> print(L1) of numbers. Increment the list value by 1 if it is Even [34, 45, 67, 89] otherwise decrement by 1. Show both original and If upper limit goes beyond range, python does not report updated list elements. any error. It simply returns elements from start range to Joining lists (+): The concatenation operator (+) joins valid final range-1 two lists. For example: Example 4: L1=[2,4] >>> L=[10,20,30,40] L2=[1,3,5] >>> L1=L[0:4:2] F=L1+L2 >>> print(L1) will produce a 3rd list F containing elements from L1 & [10, 30] then L2 It has displayed all elements starting from 0 in step 2 print(F) (i.e. after every alternate index) [2,4,1,3,5] Example 5: Example 2: >>>L=[10, 20, 30, 40] >>> [1, 2, 3] + [4, 5, 6] >>> L[:-1] [1, 2, 3, 4, 5, 6] [10, 20, 30] Note: It is important to know that ‘+’ operator in lists Example 6: expects the same type of sequence on both the sides >>>L=[10, 20, 30, 40] otherwise we get a type error. >>> L[::-1] [40, 30, 20, 10] [1, 5, 7] Example 7: Example: >>>L=[10, 20, 30, 40] >>>L=[1, 5, 7, 8, 34, 5] >>> L[::-2] >>> L.remove(5) [40, 20] >>> L [1, 7, 8, 34, 5] Deleting Elements from list: It has removed the first occurrence of given value. It is possible to delete/remove element(s) from an Note: existing list. There are many ways of doing this: i) All the methods, modify the list, after deletions. i) If index is known, pop ( ) or del can be used ii) If an out of range index is provided with del ( ) and ii) If the element is known, not the index, remove ( ) can pop ( ), the code will result in to run-time error. be used. iii) del & pop() can be used with negative index value iii) To remove more than one element, del ( ) with list also. slice can be used. iv) Using assignment operator Other functions & methods: insert(): This method inserts an element, at the given pop( ): It removes the element from the specified index, position specified by its index, and the remaining and also return the element which was removed. elements are automatically shifted to accommodate the Its syntax is: new element. Its syntax is: List.pop ([index]) list. insert (index, DataItem) Example: Index specifies the position (starting from 0) & DataItem >>>L1 = [1, 2, 5, 4, 70, 10, 90, 80, 50] is the element to be inserted in the list. Length of list >>>a=L1.pop(1) # here the element deleted will be changes after insert operation. Example returned to ‘a’ >>> L=[10,50,80] >>>print(L1) >>> L.insert(1,100) [1, 5, 4, 70, 10, 90, 80, 50] >>> L >>>print(a) [10, 100, 50, 80] 2 Note: If the index specified is greater than length of list, If we do not provide any index to pop( ), then last the object is inserted in the last. For example: element is deleted and returned. >>>L=[10, 100, 50, 80] >>>L1.pop ( ) >>> L.insert (6, 29) 50 will produce: pop() method is useful only when we want to keep the [10, 100, 50, 80, 29] element being deleted for later use. >>> L.insert (-2, 46) >>>print(L) del statement: del removes the specified element from will produce: the list, but does not return the deleted value. [10, 100, 50, 46, 80, 29] Syntax: >>> L.insert (-7, 200) del list[index] >>>print(L) OR will produce: del list[<start index>:<stop index>] [200, 10, 100, 50, 46, 80, 29] L1=[1, 5, 4, 70, 10, 90, 80, 50] >>> del L1 [4] reverse( ): This method can be used to reverse the >>> print(L1) elements of the list in place & does not return anything. [1, 5, 4, 70, 90, 80, 50] Its syntax is: >>>del L1[3:5] list.reverse ( ) >>>print(L1) Example: [1,5, 4, 80,50] >>>L=[200, 10, 100, 50, 46, 80, 29] >>> L.reverse ( ) remove(): In case, we know the element to be deleted >>> print(L) not the index, of the element, then remove ( ) can be will produce used. [29, 80, 46, 50, 100, 10, 200] L1=[1,5,6,7] Following will also result into reversed list. >>> L1. remove (6) >>>L [: : -1] will remove the value 6 from the list [200, 10, 100, 50, 46, 80, 29] >>> print(L1) It will slice the whole sequence with the step of -1 i.e. in sorted():This function arranges the data items of the list reverse order without actually reversing the list data in ascending order by default and returns a new list. Its elements. For ex.: syntax is as follows: >>> L sorted(List, key=<key value>, reverse=True/False) [29, 80, 46, 50, 100, 10, 200] Where: But reverse slicing can be stored permanently in another ➢ The <key-value> defines the key to be used for list as follows: sorting >>> L1=L[::-1] ➢ Reverse takes either True (for descending order) or >>> L False (for ascending order by default) [29, 80, 46, 50, 100, 10, 200] Example-1: >>> L1 >>> L=['k', 'a', 'c', 'v', 'o'] [200, 10, 100, 50, 46, 80, 29] >>> sorted(L) ['a', 'c', 'k', 'o', 'v'] sort ( ): This function arranges the data items of the list Example-2: in ascending order by default without creating a new list. >>> NUM=[9,3,6,1,0,-4] Its syntax is as follows: >>> sorted(NUM) List.sort(key=<key value>, reverse=True/False) [-4, 0, 1, 3, 6, 9] Where: Example-3: ➢ The <key-value> defines the key to be used for To sort the list in descending order using sort( ), we can sorting write as: ➢ Reverse takes either True (for descending order) or >>>NUM=[-4, 0, 1, 3, 6, 9] False (for ascending order by default) >>> sorted(NUM,reverse=True) Example-1: >>>NUM >>> L=['k', 'a', 'c', 'v', 'o'] [9, 6, 3, 1, 0, -4] >>> L.sort() Example-4: >>> L >>> L=['Delhi', 'Chennai', 'Mumbai'] ['a', 'c', 'k', 'o', 'v'] >>> sorted(L) Example-2: ['Chennai', 'Delhi', 'Mumbai'] >>> NUM=[9,3,6,1,0,-4] Example-5: >>> NUM.sort() >>>L=['Chennai', 'Delhi', 'Mumbai'] >>> NUM >>> sorted(L,key=len) [-4, 0, 1, 3, 6, 9] ['Delhi', 'Mumbai', 'Chennai'] Example-3: To sort the list in descending order using sort( ), we can extend( ): This function is used to add a list/tuple write as: (multiple elements) at the end of an existing list. Its >>>NUM=[-4, 0, 1, 3, 6, 9] syntax is: >>>NUM.sort(reverse=True) List.extend(<List>) >>>NUM - takes only one argument of list/tuple type & [9, 6, 3, 1, 0, -4] does not return any value Example-4: Example 1: >>> L=['Delhi', 'Chennai', 'Mumbai'] >>> L=[2, 1, 5, 6, 2] >>> L.sort() >>> L2=[1, 2, 2, 5, 6] >>> L >>> L.extend(L2) ['Chennai', 'Delhi', 'Mumbai'] >>> L Example-5: [2, 1, 5, 6, 2, 1, 2, 2, 5, 6] >>>L=['Chennai', 'Delhi', 'Mumbai'] >>> L.sort(key=len) Example 2: >>> L >>> L=[2, 1, 5, 6, 2] ['Delhi', 'Mumbai', 'Chennai'] >>> L.extend([34,56,67]) Here we have specified len( ) built in function, as key for >>> L sorting. So the list will get sorted by the length of the [2, 1, 5, 6, 2, 34, 56, 67] strings, i.e., from the shortest to the longest. sort( ) will Example 3: call len( ) function for each element of list and then these >>> L=[2, 1, 5, 6, 2] lengths will be used for arranging elements. >>> L.extend(34, 56) #will report syntax/type error Example 4: >>> L=[1,2,3,4] >>> max(L) >>> L.extend((8,9)) 'wind' >>> L >>> max('Ram') [1, 2, 3, 4, 8, 9] 'm' Example 5: min(): It returns the smallest data element from the L=[1, 2, 3, 4, 5, 6, 7, 8, 9] given iterable sequential data structure. For example: >>> L.extend('Shyama') >>> min([2,4,1,8]) >>> L 1 [1, 2, 3, 4, 5, 6, 7, 8, 9, 'S', 'h', 'y', 'a', 'm', 'a'] >>> L=[56,-3,67,12] >>> min(L) index(x): It returns the index in the list of the first item -3 whose value is x. It reports an error if there is no such sum(): It returns the sum of all data element from the item in the list. Its syntax is: given iterable sequential data structure. For example: List.index(<Value>) >>> L=[2,4,3,7] Example : >>> sum(L) >>>L= [3,5,7,4,8] 16 >>>L.index(7) This function can have second argument also as initial 2 value to start the sum with. For example: >>>L.index(9) >>> L=[2,4,3,7] Traceback (most recent call last): >>> sum(L,500) File "<pyshell#1>", line 1, in <module> 516 [3,5,7,4,8].index(9) ValueError: 9 is not in list LISTS Vs STRINGS: Similarity: count(): This function returns the number of times the ❖ len( ) function returns the number of data items specified element appears in the list. both in List & Strings Syntax: ❖ Indexing & Slicing can be done in both List.count(element) ❖ Membership operators ‘in’ & ‘not in’ are Example 1: applicable on both types list1 = ['red', 'green', 'blue', 'orange', 'green', 'gray', ❖ Concatenation (+) & Replication (*) are also 'green'] applied in both colcnt= list1.count('green') Difference: print('The count of color: green is ', colcnt) ➢ Lists are mutable while Strings are immutable Output: ➢ In consecutive locations, Lists store the The count of color: green is 3 references of its elements while strings store the Example 2: individual characters list = [2,3,4,3,10,3,5,6,3] ➢ Lists store different types of data elements while elmcount = list.count(3) Strings store only characters. print('The count of element: 3 is ', elmcount) Output: The count of element: 3 is 4 Example 3: >>> list = [2,3,4,3,10,3,5,6,3] >>> list.count(12) 0 max(): It returns the largest data element from the given iterable sequential data structure. For example: >>> max([2,4,1,8]) 8 >>> L=[56,-3,67,12] >>> max(L) 67 >>L=['p','w'] >>> max(L) 'w' >>> L=['pawan','wind']