Diese Präsentation wurde erfolgreich gemeldet.
Die SlideShare-Präsentation wird heruntergeladen. ×

Module-2.pptx

Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Nächste SlideShare
List_tuple_dictionary.pptx
List_tuple_dictionary.pptx
Wird geladen in …3
×

Hier ansehen

1 von 94 Anzeige

Weitere Verwandte Inhalte

Ähnlich wie Module-2.pptx (20)

Aktuellste (20)

Anzeige

Module-2.pptx

  1. 1. Module-2
  2. 2. What are Lists ?  Container is an entity which contains multiple data items . It is also known as a collection or a compound data type.  Python has following container datatypes : Lists Tuples Sets Dictionaries  A list is a value that contains multiple values in an ordered sequence.  A list can grow or shrink during execution of the program. Hence it is also known as a dynamic array. Because of this nature of lists they are commonly used for handling variable length data.  A list is defined by writing comma-separated elements within [ ]. num=[10,20,30,40,100] names=['sanjay','anil','radha','suparna']  A list can contain dissimilar types , though usually they are collection of similar types. animal=['Zebra',155.55,110]
  3. 3.  Items in a list can be repeated i.e., a list may contain duplicate items. Like printing , * can be used to repeat an element multiple time. An empty list is also feasible. ages=[25,26,25,27,26] num=[10]*5 lst=[] Acessing List Elements  Entire list can be printed by just using the name of the list. ages=[25,26,25,27,26] print(ages) print(ages[0],ages[3]) ages=[25,26,25,27,26] num=[10]*5 lst=[] print(ages,num,lst) spam = ['cat', 'bat', 'rat', 'elephant'] print('The ' + spam[1] + ' ate the ' + spam[0] + '.')
  4. 4.  Lists can also contain other list values. The values in these lists of lists can be accessed using multiple indexes, like so: spam = [['cat', 'bat'], [10, 20, 30, 40, 50]] print(spam[0],spam[1],spam[0][1],spam[1][4])  Negative Indexes : While indexes start at 0 and go up, you can also use negative integers for the index. The integer value -1 refers to the last index in a list, the value -2 refers to the second-to-last index in a list, and so on. spam = ['cat', 'bat', 'rat', 'elephant'] print(spam[-1],spam[-3],'The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.',sep='...! ')  Lists can be sliced Example 1: animal=['Zebra',155.55,110,'abc'] print(animal[1:3]) print(animal[3:]) Example 2: spam = ['cat', 'bat', 'rat', 'elephant'] print(spam[0:4],spam[1:3],spam[0:-1],sep='....') print(spam[:2],spam[1:],spam[:],sep=' ')  Getting a List’s Length with the len() Function spam = ['cat', 'dog', 'moose'] len(spam)
  5. 5.  Python will give you an IndexError error message if you use an index that exceeds the number of values in your list value. spam = ['cat', 'bat', 'rat', 'elephant'] spam[10000] Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> spam[10000] IndexError: list index out of range  Indexes can be only integer values, not floats. The following example will cause a TypeError error: >>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam[1] 'bat' >>> spam[1.0]
  6. 6. Looping in Lists  If we wish to process each item in the list , we should be able to iterate through the list. This can be done using a while or for loop. animals=['Zebra','Tiger','Lion','Jackal','Kangaroo'] i=0 while i<len(animals): print(animals[i]) i=i+1 for a in animals: print(a)  While iterating through a list using a for loop, if we wish to keep track of index of the element that a is referring to, we can do so using the built-in enumerate() function. animals=['Zebra','Tiger','Lion','Jackal','Kangaroo'] for index,a in enumerate(animals): print(index,a)
  7. 7. Basic List Operations #Mutability animals=['Zebra','Tiger','Lion','Jackal','Kangaroo'] ages=[25,26,25,27,26,28,25] print(animals,ages,sep="n") ages[2]=30 print(ages) ages[2:5]=[41,42,43] print(ages) ages[2:5]=[] print(ages) #Concatenation lst=[12,15,13,23,22,16,17] lst=lst+[33,44,55] print(lst)
  8. 8. #Conversion: A string/tuple/set can be converted into a list using the list() conversion function l=list('africa') print(l) #Aliasing-On assigning one list to another, both refer to the same list. Changing one changes the other. This assignment is often known as shallow copy or aliasing lst1=[10,20,30,40,50] lst2=lst1 print(lst2) lst2[2]=5 print(lst1)
  9. 9. #Cloning-This involves copying contents of one list into another . After copying both refer to different lists, though both contain same values. Changing one list, doesn't change same values. Changing one list, doesn't change another. This operation is often known as deep copy lst1=[10,20,30,40,50] lst2=[] lst2=lst2+lst1 print("lst1= ",lst1,"n","lst2= ",lst2) lst2[0:5]=[60,70,80,90,100] print(lst1,lst2,sep='n') #Searching-An element can be searched in a list using the in membership operator as shown below: lst=['a','e','i','o','u'] res='a' in lst print(res) res='z' not in lst print(res)
  10. 10. #Identity- Whether the two variables are referring to the same list can be checked using the is identity operator lst1=[10,20,30,40,50] lst2=[10.20,30,40,50] lst3=lst2 print(lst1 is lst2) print(lst1 is lst3) print(lst2 is lst3) print(lst1 is not lst2) num1=10 num2=10 s1='Hi' s2='Hi' print(num1 is num2) print(s1 is s2)
  11. 11. #Comparison- It is possible to compare contents of two lists. Comparision is done item by item till there is a mismatch. a=[1,2,3,4] b=[1,2,5] print(a<b) #Emptiness- We can check if a list is empty using not operator lst=[] if not lst: print('Empty list') Alternatively… lst=[] print(bool(lst))
  12. 12. Using Built-in Functions on lists: 1. len(lst) #return number of items in the list. 2. max(lst) #return maximum element in the list. 3. min(lst) #return minimum element in the list. 4. sum(lst) #return sum of all elements in the list. 5. any(lst) #return True if any element of lst is True 6. all(lst) #return True if all elements of lst is True 7. del(lst) #deletes element or slice or entire list. 8. sorted(lst) #return sorted list,lst remains unchanged 9. reversed(lst) #used for reversing list del lst=[10,20,30,40,50] del(lst[3]) print(lst) del(lst[2:5]) print(lst) lst=[10,20,30,40,50] del(lst[:]) print(lst) lst=[10,20,30,40,50] lst=[] print(lst)
  13. 13. '''If multiple variables are referring to same list ,then deleting one doesn't delete the others''‘ lst1=[10,20,30,40,50] lst3=lst2=lst1 lst1=[] print(lst2) print(lst3) '''If multiple variables are referring to same list and we wish to delete all,we can do so as shown below''' lst1=[10,20,30,40,50] lst3=lst2=lst1 lst1[:]=[] print(lst2) print(lst3)
  14. 14. Iist Methods : Any list is an object of type list.Its methods can be accessed using the syntax lst.method(). lst=[12,15,13,23,22,16,17] #create list lst.append(22) #add new item at end print(lst) lst.remove(13) #delete 13 from list print(lst) #lst.remove(30) #reports valueError as 30 is absent in lst lst.pop() #removes last item in lst print(lst) lst.pop(3) #removes 3rd item in the lst print(lst) lst.insert(3,21) #insert 21 at 3rd position print(lst) lst.count(23) #return no. of times 23 appear in the list print(lst) idx=lst.index(17) #return index of item 22 print(lst) #idx=lst.index(50) #reports valueError as 50 is absent in the list
  15. 15. #Sorting and Reversing lst=[10,2,0,50,4] lst.reverse() print(lst) lst.sort() print(lst) lst.sort(reverse=True) print(lst) [4, 50, 0, 2, 10] [0, 2, 4, 10, 50] [50, 10, 4, 2, 0] Note: reverse() and sort() do not return a list. Both manipulate the list in place.
  16. 16. #Usage of bulitin functions for reversing and sorting a list. lst=[10,2,0,50,4] print(sorted(lst)) print(sorted(lst,reverse=True)) print(list(reversed(lst))) print(lst) [0, 2, 4, 10, 50] [50, 10, 4, 2, 0] [4, 50, 0, 2, 10] [10, 2, 0, 50, 4] #Reversal is also possible using a slicing operation lst=[10,2,0,50,4] print(lst[::-1])
  17. 17. List Varieties:It is possible to create a list of lists a=[1,3,5,6,7] b=[2,4,6,8,10] c=[a,b] print(c[0][0],c[1][2]) 1 6 A list may be embedded in another list x=[1,2,3,4] y=[10,20,x,30] print(y) [10, 20, [1, 2, 3, 4], 30] It is possible to unpack a string or list within a list using the * operator s='Hello' l=[*s] print(l) x=[1,2,3,4] y=[10,20,*x,30] print(y) ['H', 'e', 'l', 'l', 'o'] [10, 20, 1, 2, 3, 4, 30]
  18. 18. 1. Perform the following operation on a list of names. i. Create a list of 5 names-’Anil’, ’Amol’, ’Adtiya’, ’Avi’ , ’Alka’ ii. Insert a name ‘Anju’ before Aditya iii. Append a name ‘Zulu’ iV.Delete ‘Avi’ from the list v. Replace ‘Anil’ with ‘AnilKumar’ vi. Sort all the names in the list vii. Print reversed sorted list
  19. 19. 2. Perform the following operation on a list of numbers 1. Create a list of odd numbers 2. Create a list of even numbers 3. Combine the two lists 4. Add prime numbers 11,17,29 at the beginning of the combined list. 5. Report how many elements are present in the list 6. Replace last 3 numbers in the list with 100,200,300 7. Delete all the numbers in the list 8. Delete the list
  20. 20. 3. Write a program to implement a Stack data structure. Stack is a Last In First Out(LIFO) list in which addition and deletion takes place at the same end stack = [] # append() function to push # element in the stack stack.append('a') stack.append('b') stack.append('c') print('Initial stack') print(stack) # pop() function to pop # element from stack in # LIFO order print('nElements popped from stack:') print(stack.pop()) print(stack.pop()) print(stack.pop()) print('nStack after elements are popped:') print(stack)
  21. 21. 4. Write a program to implement a Queue data structure. Queue is a First In First Out (FIFO) list, in which addition takes place at the rare end of the queue and deletion takes place at the front end of the queue. # Initializing a queue queue = [] # Adding elements to the queue queue.append('a') queue.append('b') queue.append('c') print("Initial queue") print(queue) # Removing elements from the queue print("nElements dequeued from queue") print(queue.pop(0)) print(queue.pop(0)) print(queue.pop(0)) print("nQueue after removing elements") print(queue)
  22. 22. 5. Write a program to generate and store in a list 20 random numbers in the range 10 to 100.From this list delete all those entries which value between 20 and 50. Print the remaining list. import random a=[] i=1 while i<=15: num=random.randint(10,100) a.append(num) i+=1 print(a) for num in a: if num>20 and num < 50: a.remove(num) print(a)
  23. 23. 6. Write a program to add two 3X4 matrices X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] result = [[0,0,0], [0,0,0], [0,0,0]] # iterate through rows for i in range(len(X)): # iterate through columns for j in range(len(X[0])): result[i][j] = X[i][j] + Y[i][j] for r in result: print(r)
  24. 24. What are tuples?  Though a list can store dissimilar data,it is commonly used for storing similar data.  Though a tuple can store similar data it is commonly used for storing dissimilar data. The tuple data is enclosed within ( ). a=() b=(10,) #if we donot use the comma after 10,b is treated to be of type int c=('Sanjay',25,34555.50) d=(10,20,30,40)  While initializing a tuple, we may drop () c='Sanjay',25,34555.50 print(type(c)) <class 'tuple'>  Items in a tuple can be repeated, i.e., tuple may contain duplicate items. However, unlike list,tuple elements cannot be repeated using a *. tpl1=(10,)*5 tpl2=(10)*5 print(tpl1) print(tpl2) (10, 10, 10, 10, 10) 50
  25. 25. Accessing Tuple Elements  Entire tuple can be printed by just the name of the tuple. tpl=('Sanjay',25,34555.50) print(tpl)  Tuple is an ordered collection. So, order of insertion of elements in a tuple is same as the order of access. So, like a string and list, tuple items too can be accessed using indices, starting with 0. tpl=('Sanjay',25,34555.50) print(tpl[0],tpl[1])  Like strings and lists, tuples too can be sliced to yield smaller tuples. tpl=('Sanjay',25,34555.50,'suneetha') print(tpl[1:3],tpl[2:],tpl[:3],sep='n') (25, 34555.5) (34555.5, 'suneetha') ('Sanjay', 25, 34555.5)
  26. 26. Looping in Tuples  If we wish to process each item in the tuple , we should be able to iterate through the list. This can be done using a while or for loop. tpl=(10,20,30,40,50) i=0 while i<len(tpl): print(tpl[i]) i=i+1 for n in tpl: print(n)  While iterating through a list using a for loop, if we wish to keep track of index of the element that a is referring to, we can do so using the built-in enumerate() function. animals=('Zebra','Tiger','Lion','Jackal','Kangaroo') for index,a in enumerate(animals): print(index,a)
  27. 27. Basic Tuple Operations:  Mutability-Unlike a list, atuple is immutable, i.e., it cannot be modified. msg=('fall','in','line') msg[0]='FALL‘ #Error msg[0:3]=('Above','Mark') #Error  Since a tuple is immutable operations like append,remove and insert do not work with tuple.  Though a tuple itself is immutable, it can contain mutable objects like lists. If a tuple contains a list, the list can be modified since list is a mutable object. s=([1,2,3,4],[4,5],'Ocelot') s[1][1]=45 print(s)  Other operations that can be performed on tuple are: Concatenation,Merging,Conversion,Aliasing,Cloning,Searching,Identity,Comparison,Emptiness.
  28. 28. Using Built-in Functions on Tuples t=(12,15,13,23,22,16,17) len(t) print(t) max(t) print(t) min(t) print(t) sum(t) print(t) any(t) print(t) all(t) print(t) sorted(t) print(t) tuple(reversed(t))
  29. 29. Tuple methods • It is possible to create a tuple of tuples. a=(1,3,5,7,9) b=(2,4,6,8,10) c=(a,b) print(c[0][0],c[1][2]) records=( ('Priyanka',24,3455.50),('shailesh',25,4555.50), ('subash',25,4505),('Sugandh',27,4455.55) ) print(records[0][0],records[0][1],records[0][2]) for n,a,s in records: print(n,a,s)
  30. 30. • A tuple may be embedded in another tuple. x=(1,2,3,4) y=(10,20,x,30) print(y) • It is possible to unpack a tuple within a tuple using the * operator x=(1,2,3,4) y=(10,20,*x,30) print(y) • It is possible to create a list of tuples, or a tuple of list. lst=[('Priyanka',24,3455.50),('shailesh',25,4555.50)] tpl=(['Priyanka',24,3455.50],['shailesh',25,4555.50])
  31. 31. Pass a tuple to the divmod() function and obtain the quotient and remainder result=divmod(17,3) print(result) t=(17,3) result=divmod(*t) print(result)
  32. 32. Write a python program to perform the following operations: 1. Pack first 10 multiples of 10 into tuple 2. Unpack the tuple in to 10 variables,each holding 1 value. 3. Unpack the tuple such that first value gets stored in variable x,last value in y and all values in between into disposable variable _ 4. Unpack the tuple such that first value gets stored in variable I, last value in j and all values in between into single disposable variable _ tpl=(10,20,30,40,50,60,70,80,90,100) a,b,c,d,e,f,g,h,i,j=tpl print(tpl) print(a,b,c,d,e,f,g,h,i,j) x,_,_,_,_,_,_,_,_,y=tpl print(x,y,_) i,*_,j=tpl print(i,j,_)
  33. 33. A list contains names of boys and girls as its elements.Boy’s names are stored as tuples. Write a python program to find out number of boys and girls in the list. lst=['Shubha','Nisha','Sudha',('suresh',),('Rajesh',),'Radha'] boys=0 girls=0 for ele in lst: if isinstance(ele,tuple): boys+=1 else: girls+=1 print('Boys=',boys,'Girls=',girls)
  34. 34. A list contains tuples containing roll number,names and age of student. Write a python program to gather all the names from this list into another list lst=[('A101','Shubha',23),('A104','Nisha',23),('A111','Sudha',23)] nlst=[] for ele in lst: nlst=nlst+[ele[1]] print(nlst)
  35. 35. Given the following tuple (‘F’,’l’,’a’,’b’,’b’,’e’,’r’,’g’,’a’,’s’,’t’,’e’,’d’) Write a python program to carry out the following operations: • Add an ! at the end of the tuple • Convert a tuple to a string • Extract (‘b’,’b’) from the tuple • Find out number of occurrence of ‘e’ in the tuple • Check whether ‘r’ exists in the tuple • Convert the tuple to a list • Delete characters ‘b’,’b’,’e’,’r’ from the tuple
  36. 36. tpl=('F','l','a','b','b','e','r','g','a','s','t','e','d') tpl=tpl+('!',) print(tpl) s="".join(tpl) print(s) t=tpl[3:5] print(t) count=tpl.count('e') print('count=',count) print('r' in tpl) lst=list(tpl) print(lst) tpl=tpl[:3]+tpl[7:] print(tpl) ('F', 'l', 'a', 'b', 'b', 'e', 'r', 'g', 'a', 's', 't', 'e', 'd', '!') Flabbergasted! ('b', 'b') count= 2 True ['F', 'l', 'a', 'b', 'b', 'e', 'r', 'g', 'a', 's', 't', 'e', 'd', '!'] ('F', 'l', 'a', 'g', 'a', 's', 't', 'e', 'd', '!')
  37. 37. Sets:  Sets are like lists,with an exception that they donot contain duplicate entries. a=set() #empty set use () instead of {} b={20} c={'Sanjay',25,34555.50} d={10,10,10}  While storing an element in a set, its hash value is computed using a hashing technique to determine where it should be stored in the set.  Since hash value of an element will always be same, no matter in which order we insert the elements in a set, they get stored in the same order. s={12,23,45,16,52} t={16,52,12,23,45} u={52,12,16,45,23} print(s) print(t) print(u)  It is possible to create a set of strings and tuples, but not a set of lists. s1={'Morning','Evening'} s2={(12,23),(15,25),(17,34)} s3={[12,23],[15,25],[17,34]} #unhashable type: 'list'
  38. 38.  Since strings ad tuples are immutable, their hash value remains same at all times. Hence a set of strings or tuples is permitted . However , a list may change, so its hash value may change, hence a set of list is not permitted.  Sets are commonly used for eliminating duplicate entries and membership testing. Accessing Set elements  Entire set can be printed by just using the name of the set.Set is an unordered collection. Hence order of insertion is not same as the order of access. s={12,23,45,16,52} print(s)  Being an ordered collection, items in a set cannot be accessed using indicies.  Sets cannot be sliced using [ ].
  39. 39. Looping in Sets Sets can be iterated over using only for loop s={12,23,45,16,52} for ele in s: print(ele) Built in function enumerate() can be used with a set. The enumeration is done on access order, not insertion order. s={12,15,13,23,22,16,17} for index,ele in enumerate(s): print(index,ele)
  40. 40. Basic Set Operation  Sets like lists are mutable. Their contents can be changed. s={'gate','fate','late'} s.add('rate')  If we want an immutable set, we should use a frozenset. s=frozenset({'gate','fate','late'}) s.add('rate') #Error  Other operations that can be performed on set are: Conversion,Aliasing,Cloning,Searching,Identity,Comparison,Emptiness Doesnot Work:Concatenation,Merging.  While converting a set using set(), repetitions are eliminated. lst=[10,20,10,30,40,50,30] s=set(lst)
  41. 41. Using Built-in Function t={12,15,13,23,22,16,17} print(len(t)) print(max(t)) print(min(t)) print(sum(t)) print(any(t)) print(all(t)) print(sorted(t)) # reversed() built-in function doesn't work on sets.
  42. 42. References >>> spam = 42 >>> cheese = spam >>> spam = 100 >>> spam 100 >>> cheese 42 ➊ >>> spam = [0, 1, 2, 3, 4, 5] ➋ >>> cheese = spam # The reference is being copied, not the list. ➌ >>> cheese[1] = 'Hello!' # This changes the list value. >>> spam [0, 'Hello!', 2, 3, 4, 5] >>> cheese # The cheese variable refers to the same list. [0, 'Hello!', 2, 3, 4, 5]
  43. 43. Identity and the id() Function All values in Python have a unique identity that can be obtained with the id() function. >>> id('Howdy') # The returned number will be different on your machine. 44491136 >>> bacon = 'Hello' >>> id(bacon) 44491136 >>> bacon += ' world!' # A new string is made from 'Hello' and ' world!'. >>> id(bacon) # bacon now refers to a completely different string. 44609712 >>> eggs = ['cat', 'dog'] # This creates a new list. >>> id(eggs) 35152584 >>> eggs.append('moose') # append() modifies the list "in place". >>> id(eggs) # eggs still refers to the same list as before. 35152584 >>> eggs = ['bat', 'rat', 'cow'] # This creates a new list, which has a new identity. >>> id(eggs) # eggs now refers to a completely different list. 44409800
  44. 44. If two variables refer to the same list (like spam and cheese in the previous section) and the list value itself changes, both variables are affected because they both refer to the same list. The append(), extend(), remove(), sort(), reverse(), and other list methods modify their lists in place. Python’s automatic garbage collector deletes any values not being referred to by any variables to free up memory. You don’t need to worry about how the garbage collector works, which is a good thing: manual memory management in other programming languages is a common source of bugs. Passing References def eggs(someParameter): someParameter.append('Hello') spam = [1, 2, 3] eggs(spam) print(spam) [1, 2, 3, 'Hello']
  45. 45. The copy Module’s copy() and deepcopy() Functions Although passing around references is often the handiest way to deal with lists and dictionaries, if the function modifies the list or dictionary that is passed, you may not want these changes in the original list or dictionary value. For this, Python provides a module named copy that provides both the copy() and deepcopy() functions. The first of these, copy.copy(), can be used to make a duplicate copy of a mutable value like a list or dictionary, not just a copy of a reference. >>> import copy >>> spam = ['A', 'B', 'C',[1,2,3], 'D'] >>> id(spam) 44684232 >>> cheese = copy.copy(spam) >>> id(cheese) # cheese is a different list with different identity. 44685832 >>> cheese[1] = 42 >>> spam ['A', 'B', 'C', 'D'] >>> cheese ['A', 42, 'C', 'D']
  46. 46. If the list you need to copy contains lists, then use the copy.deepcopy() function instead of copy.copy(). The deepcopy() function will copy these inner lists as well.
  47. 47. What is Deep copy in Python? A deep copy creates a new compound object before inserting copies of the items found in the original into it in a recursive manner. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. In the case of deep copy, a copy of the object is copied into another object. It means that any changes made to a copy of the object do not reflect in the original object.
  48. 48. # importing "copy" for copy operations import copy # initializing list 1 li1 = [1, 2, [3,5], 4] # using deepcopy to deep copy li2 = copy.deepcopy(li1) # original elements of list print ("The original elements before deep copying") for i in range(0,len(li1)): print (li1[i],end=" ") print("r") # adding and element to new list li2[2][0] = 7 # Change is reflected in l2 print ("The new list of elements after deep copying ") for i in range(0,len( li1)): print (li2[i],end=" ") print("r") # Change is NOT reflected in original list # as it is a deep copy print ("The original elements after deep copying") for i in range(0,len( li1)): print (li1[i],end=" ") Output: The original elements before deep copying 1 2 [3, 5] 4 The new list of elements after deep copying 1 2 [7, 5] 4 The original elements after deep copying 1 2 [3, 5] 4
  49. 49. What is Shallow copy in Python? A shallow copy creates a new compound object and then references the objects contained in the original within it, which means it constructs a new collection object and then populates it with references to the child objects found in the original. The copying process does not recurse and therefore won’t create copies of the child objects themselves. In the case of shallow copy, a reference of an object is copied into another object. It means that any changes made to a copy of an object do reflect in the original object. In python, this is implemented using the “copy()” function.
  50. 50. # importing "copy" for copy operations import copy # initializing list 1 li1 = [1, 2, [3,5], 4] # using copy to shallow copy li2 = copy.copy(li1) # original elements of list print ("The original elements before shallow copying") for i in range(0,len(li1)): print (li1[i],end=" ") print("r") # adding and element to new list li2[2][0] = 7 # checking if change is reflected print ("The original elements after shallow copying") for i in range(0,len( li1)): print (li1[i],end=" ")
  51. 51. What are Dictionaries? Dictionary is a collection of key-value pairs. Dictionary are also known as maps or associative arrays. A Dictionary contains comma separated key : value pair enclosed within { }. d1={ } d2={'A101':'Amol','A102':'Anil','B103':'Ravi'} Different keys may have same values. d={10:'A',20:'A',30:'B'} Keys must be unique. If keys are same, but values are different, latest key value pair gets stored. d={10:'A',20:'A',10:'B'} {10: 'B', 20: 'A'} If key value pair are repeated, then only one pair gets stored.
  52. 52. Accessing Dictionary Elements Entire dictionary can be printed by just using the name of the dictionary. d={'A101':'Amol','A102':'Anil','B103':'Ravi'} print(d) Unlike sets, dictionaries preserve insertion order. However, elements are not accessed using the position, but using the key. d2={'A101':'Amol','A102':'Anil','B103':'Ravi'} print(d2['A102']) Dictionaries cannot be sliced using [ ].
  53. 53. Looping in Dictionaries Like strings,lists,tuples and sets, dictionaries too can be iterated over using a for loop.There are three ways to do so. courses={'DAA':'CS','AOA':'ME','SVY':'CE'} for k,v in courses.items(): print(k,v) for k in courses.keys(): print(k) for v in courses.values(): print(v) for k in courses: print(k) for v in courses: print(v)
  54. 54. While iterating through a dictionary using for loop, if we wish to keep track of index of the key-value pair that is being referred to, we can do so using the built-in enumerate() function. courses={'DAA':'CS','AOA':'ME','SVY':'CE'} for i,(k,v) in enumerate(courses.items()): print(i,k) Basic Dictionary operations Dictionaries are mutable.So, we can perform add/delete/modify operations on dictionary. courses={'DAA':'CS','AOA':'ME','SVY':'CE'} courses['ATCI']='CS/IS' courses['DAA']='CS/IS' del[courses['DAA']] print(courses) Any new addition will takes place at the end of the existing dictionary, since dictionary preserves the insertion order. Dictionary keys cannot be changed in place.
  55. 55. Operations on dictionaries: Concatenation,Merging,Comparision-Doesn't work Conversion,Cloning,Identity,Emptiness,Aliasing,Searching,ComparisonWorks Built-in functions: c={'DAA':'CS','AOA':'ME','SVY':'CE'} print(len(c)) print(max(c)) print(min(c)) print(sorted(c)) #print(sum(c)) print(any(c)) print(all(c)) print(reversed(c)) c={'DAA':'CS','AOA':'ME','SVY':'CE'} for k,v in reversed(c.items()): print(k,v)
  56. 56. Dictionary Methods c={'DAA':'CS','AOA':'ME','SVY':'CE'} d={'ME126':'HPE','ME102':'TOM','ME234':'AEM'} print(c.get('DAA','Absent')) print(c.get('EE102','Absent')) c.update(d) print(c.popitem()) print(c.pop('ME126')) c.clear()
  57. 57. Dictionary varieties
  58. 58. dict1.update(dict2)The dictionary dict2’s key-value pair will be updated in dictionary dict1. dict1={'Name':'Tom','Age':20,'Height':160} print(dict1) dict2={'Weight':60} print(dict2) dict1.update(dict2) print("dict1 updated dict2: ",dict1) {'Name': 'Tom', 'Age': 20, 'Height': 160} {'Weight': 60} dict1 updated dict2: {'Name': 'Tom', 'Age': 20, 'Height': 160, 'Weight': 60}
  59. 59. in operator & _ _contains_ _(key)-Returns True , if the key is in the dictionary dict, else False is returned. dict1={'Name':'Tom','Age':20,'Height':160} print(dict1) print("Dict1.has_key(key):",dict1.__contains__('Age')) print('Age' in dict1) {'Name': 'Tom', 'Age': 20, 'Height': 160} Dict1.has_key(key): True True
  60. 60. dict1.get(key,default=None)returns the value corresponding to the key specified and if the key specified is not in the dictionary, it returns the default value dict1={'Name':'Tom','Age':20,'Height':160} print("dict1.get('Age'):",dict1.get('Age')) print("dict1.get('Phone'):",dict1.get('Phone',0)) print(dict1) dict1.get('Age'): 20 dict1.get('Phone'): 0 {'Name': 'Tom', 'Age': 20, 'Height': 160}
  61. 61. dict.setdefault(key,default=None)Similar to dict1.get(key,default=None) but will set the key with the value passed and if key is not in the dictionary, it will set with the default value. dict1={'Name':'Tom','Age':20,'Height':160} print("dict1.setdefault('Age'):",dict1.setdefault('Age')) print("dict1.setdefault('Phone'):",dict1.setdefault('Phone',0)) print(dict1) dict1.setdefault('Age'): 20 dict1.setdefault('Phone'): 0 {'Name': 'Tom', 'Age': 20, 'Height': 160, 'Phone': 0}
  62. 62. dict.fromkeys(list,[val])Creates a new dictionary from sequence seq and values from val. A dictionary containing different keys but same values can be created using fromkeys() function as shown below: list=['Name','Age','Height'] dict=dict.fromkeys(list) print("New Dictionary:",dict) New Dictionary: {'Name': None, 'Age': None, 'Height': None} Two dictionaries can be merged to create a third dictionary by unpacking the two dictionaries using ** . If we use * only keys will be unpacked. animals={'tiger':141,'Lion':152,'Leopard':110} birds={'Eagle':38,'Crow':3,'Parrot':2} combined={**animals,**birds} print(combined)
  63. 63. PRETTY PRINTING If you import the pprint module into your programs, you’ll have access to the pprint() and pformat() functions that will “pretty print” a dictionary’s values. This is helpful when you want a cleaner display of the items in a dictionary than what print() provides. message = 'It was a bright cold day in April, and the clocks were striking thirteen.' count = {} for character in message: count.setdefault(character, 0) count[character] = count[character] + 1 print(count) {'I': 1, 't': 6, ' ': 13, 'w': 2, 'a': 4, 's': 3, 'b': 1, 'r': 5, 'i': 6, 'g': 2, 'h': 3, 'c': 3, 'o': 2, 'l': 3, 'd': 3, 'y': 1, 'n': 4, 'A': 1, 'p': 1, ',': 1, 'e': 5, 'k': 2, '.': 1}
  64. 64. import pprint message = 'It was a bright cold day in April, and the clocks were striking thirteen.' count = {} for character in message: count.setdefault(character, 0) count[character] = count[character] + 1 pprint.pprint(count) {' ': 13, ',': 1, '.': 1, 'A': 1, 'I': 1, 'a': 4, 'b': 1, 'c': 3, 'd': 3, 'e': 5, 'g': 2, 'h': 3, 'i': 6, 'k': 2, 'l': 3, 'n': 4, 'o': 2, 'p': 1, 'r': 5, 's': 3, 't': 6, 'w': 2, 'y': 1}  The pprint.pprint() function is especially helpful when the dictionary itself contains nested lists or dictionaries.  If you want to obtain the prettified text as a string value instead of displaying it on the screen, call pprint.pformat() instead. These two lines are equivalent to each other: pprint.pprint(someDictionaryValue) print(pprint.pformat(someDictionaryValue))
  65. 65. Nested Dictionaries and Lists allGuests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {'ham sandwiches': 3, 'apples': 2}, 'Carol': {'cups': 3, 'apple pies': 1}} def totalBrought(guests, item): numBrought = 0 for k, v in guests.items(): numBrought = numBrought + v.get(item, 0) return numBrought print('Number of things being brought:') print(' - Apples ' + str(totalBrought(allGuests, 'apples'))) print(' - Cups ' + str(totalBrought(allGuests, 'cups'))) print(' - Cakes ' + str(totalBrought(allGuests, 'cakes'))) print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches'))) print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))
  66. 66. Strings Strings in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the same as "hello". You can display a string literal with the print() function: print("Hello") print('Hello') Assign String to a Variable Assigning a string to a variable is done with the variable name followed by an equal sign and the string: a = "Hello" print(a)
  67. 67. Multiline Strings You can assign a multiline string to a variable by using three quotes: a = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" print(a) a = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.''' print(a)
  68. 68. Strings are Arrays strings in Python are arrays of bytes representing unicode characters. Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string. a = "Hello, World!" print(a[1]) Looping Through a String Since strings are arrays, we can loop through the characters in a string, with a for loop. for x in "banana": print(x) String Length To get the length of a string, use the len() function. a = "Hello, World!" print(len(a))
  69. 69. Check String To check if a certain phrase or character is present in a string, we can use the keyword in. txt = "The best things in life are free!" print("free" in txt) txt = "The best things in life are free!" if "free" in txt: print("Yes, 'free' is present.") Check if NOT txt = "The best things in life are free!" print("expensive" not in txt) txt = "The best things in life are free!" if "expensive" not in txt: print("No, 'expensive' is NOT present.")
  70. 70. Slicing You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string. b = "Hello, World!" print(b[2:5]) Slice From the Start b = "Hello, World!" print(b[:5]) Slice To the End b = "Hello, World!" print(b[2:]) Negative Indexing Use negative indexes to start the slice from the end of the string: b = "Hello, World!" print(b[-5:-2])
  71. 71. The upper() method returns the string in upper case: a = "Hello, World!" print(a.upper()) The lower() method returns the string in lower case: a = "Hello, World!" print(a.lower()) Remove Whitespace Whitespace is the space before and/or after the actual text, and very often you want to remove this space. a = " Hello, World! " print(a.strip()) # returns "Hello, World!“ Replace String The replace() method replaces a string with another string: a = "Hello, World!" print(a.replace("H", "J"))
  72. 72. Split String The split() method returns a list where the text between the specified separator becomes the list items. Example The split() method splits the string into substrings if it finds instances of the separator: a = "Hello, World!" print(a.split(",")) # returns ['Hello', ' World!'] String Concatenation To concatenate, or combine, two strings you can use the + operator. Example Merge variable a with variable b into variable c: a = "Hello" b = "World" c = a + b print(c)
  73. 73. Example To add a space between them, add a " ": a = "Hello" b = "World" c = a + " " + b print(c) String Format As we learned in the Python Variables chapter, we cannot combine strings and numbers like this: Example age = 36 txt = "My name is John, I am " + age print(txt) But we can combine strings and numbers by using the format() method! The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are: Example Use the format() method to insert numbers into strings: age = 36 txt = "My name is John, and I am {}" print(txt.format(age))
  74. 74. The format() method takes unlimited number of arguments, and are placed into the respective placeholders: Example quantity = 3 itemno = 567 price = 49.95 myorder = "I want {} pieces of item {} for {} dollars." print(myorder.format(quantity, itemno, price)) You can use index numbers {0} to be sure the arguments are placed in the correct placeholders: Example quantity = 3 itemno = 567 price = 49.95 myorder = "I want to pay {2} dollars for {0} pieces of item {1}." print(myorder.format(quantity, itemno, price))
  75. 75. Escape Character To insert characters that are illegal in a string, use an escape character. An escape character is a backslash followed by the character you want to insert. An example of an illegal character is a double quote inside a string that is surrounded by double quotes: Example You will get an error if you use double quotes inside a string that is surrounded by double quotes: txt = "We are the so-called "Vikings" from the north.“ To fix this problem, use the escape character ": Example The escape character allows you to use double quotes when you normally would not be allowed: txt = "We are the so-called "Vikings" from the north."
  76. 76. The isX() Methods Along with islower() and isupper(), there are several other string methods that have names beginning with the word is. These methods return a Boolean value that describes the nature of the string. Here are some common isX string methods: isalpha() Returns True if the string consists only of letters and isn’t blank isalnum() Returns True if the string consists only of letters and numbers and is not blank isdecimal() Returns True if the string consists only of numeric characters and is not blank isspace() Returns True if the string consists only of spaces, tabs, and newlines and is not blank istitle() Returns True if the string consists only of words that begin with an uppercase letter followed by only lowercase letters
  77. 77. >>> 'hello'.isalpha() True >>> 'hello123'.isalpha() False >>> 'hello123'.isalnum() True >>> 'hello'.isalnum() True >>> '123'.isdecimal() True >>> ' '.isspace() True >>> 'This Is Title Case'.istitle() True >>> 'This Is Title Case 123'.istitle() True >>> 'This Is not Title Case'.istitle() False >>> 'This Is NOT Title Case Either'.istitle() False
  78. 78. The following program repeatedly asks users for their age and a password until they provide valid input. while True: print('Enter your age:') age = input() if age.isdecimal(): break print('Please enter a number for your age.') while True: print('Select a new password (letters and numbers only):') password = input() if password.isalnum(): break print('Passwords can only have letters and numbers.')
  79. 79. The startswith() and endswith() Methods The startswith() and endswith() methods return True if the string value they are called on begins or ends (respectively) with the string passed to the method; otherwise, they return False. Enter the following into the interactive shell: >>> 'Hello, world!'.startswith('Hello') True >>> 'Hello, world!'.endswith('world!') True >>> 'abc123'.startswith('abcdef') False >>> 'abc123'.endswith('12') False >>> 'Hello, world!'.startswith('Hello, world!') True >>> 'Hello, world!'.endswith('Hello, world!') True
  80. 80. The join() and split() Methods The join() method is useful when you have a list of strings that need to be joined together into a single string value. The join() method is called on a string, gets passed a list of strings, and returns a string. The returned string is the concatenation of each string in the passed-in list. >>> ', '.join(['cats', 'rats', 'bats']) 'cats, rats, bats' >>> ' '.join(['My', 'name', 'is', 'Simon']) 'My name is Simon' >>> 'ABC'.join(['My', 'name', 'is', 'Simon']) 'MyABCnameABCisABCSimon' >>> 'My name is Simon'.split() ['My', 'name', 'is', 'Simon'] >>> 'MyABCnameABCisABCSimon'.split('ABC') ['My', 'name', 'is', 'Simon'] >>> 'My name is Simon'.split('m') ['My na', 'e is Si', 'on']
  81. 81. spam = '''Dear Alice, How have you been? I am fine. There is a container in the fridge that is labeled "Milk Experiment." Please do not drink it. Sincerely, Bob''' spam.split('n') Splitting Strings with the partition() Method The partition() string method can split a string into the text before and after a separator string. This method searches the string it is called on for the separator string it is passed, and returns a tuple of three substrings for the “before,” “separator,” and “after” substrings. >>> 'Hello, world!'.partition('w') ('Hello, ', 'w', 'orld!') >>> 'Hello, world!'.partition('world') ('Hello, ', 'world', '!')
  82. 82. If the separator string you pass to partition() occurs multiple times in the string that partition() calls on, the method splits the string only on the first occurrence: >>> 'Hello, world!'.partition('o') ('Hell', 'o', ', world!') If the separator string can’t be found, the first string returned in the tuple will be the entire string, and the other two strings will be empty: >>> 'Hello, world!'.partition('XYZ') ('Hello, world!', '', '') You can use the multiple assignment trick to assign the three returned strings to three variables: >>> before, sep, after = 'Hello, world!'.partition(' ') >>> before 'Hello,' >>> after 'world!'
  83. 83. Justifying Text with the rjust(), ljust(), and center() Methods The rjust() and ljust() string methods return a padded version of the string they are called on, with spaces inserted to justify the text. The first argument to both methods is an integer length for the justified string. >>> 'Hello'.rjust(10) ' Hello' >>> 'Hello'.rjust(20) ' Hello' >>> 'Hello, World'.rjust(20) ' Hello, World' >>> 'Hello'.ljust(10) 'Hello ' >>> 'Hello'.rjust(20, '*') '***************Hello' >>> 'Hello'.ljust(20, '-') 'Hello--------------- >>> 'Hello'.center(20) ' Hello ' >>> 'Hello'.center(20, '=') '=======Hello========'
  84. 84. These methods are especially useful when you need to print tabular data that has correct spacing. def printPicnic(itemsDict, leftWidth, rightWidth): print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-')) for k, v in itemsDict.items(): print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth)) picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000} printPicnic(picnicItems, 12, 5) printPicnic(picnicItems, 20, 6) ---PICNIC ITEMS-- sandwiches.. 4 apples...... 12 cups........ 4 cookies..... 8000 -------PICNIC ITEMS------- sandwiches.......... 4 apples.............. 12 cups................ 4 cookies............. 8000
  85. 85. Removing Whitespace with the strip(), rstrip(), and lstrip() Methods Sometimes you may want to strip off whitespace characters (space, tab, and newline) from the left side, right side, or both sides of a string. The strip() string method will return a new string without any whitespace characters at the beginning or end. The lstrip() and rstrip() methods will remove whitespace characters from the left and right ends, respectively >>> spam = ' Hello, World ' >>> spam.strip() 'Hello, World' >>> spam.lstrip() 'Hello, World ' >>> spam.rstrip() ' Hello, World' Optionally, a string argument will specify which characters on the ends should be stripped. >>> spam = 'SpamSpamBaconSpamEggsSpamSpam' >>> spam.strip('ampS') 'BaconSpamEggs'
  86. 86. NUMERIC VALUES OF CHARACTERS WITH THE ORD() AND CHR() FUNCTIONS Computers store information as bytes—strings of binary numbers, which means we need to be able to convert text to numbers. Because of this, every text character has a corresponding numeric value called a Unicode code point. For example, the numeric code point is 65 for 'A', 52 for '4', and 33 for '!'. You can use the ord() function to get the code point of a one-character string, and the chr() function to get the one-character string of an integer code point. >>> ord('A') 65 >>> ord('4') 52 >>> ord('!') 33 >>> chr(65) 'A'
  87. 87. These functions are useful when you need to do an ordering or mathematical operation on characters: >>> ord('B') 66 >>> ord('A') < ord('B') True >>> chr(ord('A')) 'A' >>> chr(ord('A') + 1) 'B' COPYING AND PASTING STRINGS WITH THE PYPERCLIP MODULE The pyperclip module has copy() and paste() functions that can send text to and receive text from your computer’s clipboard. Sending the output of your program to the clipboard will make it easy to paste it into an email, word processor, or some other software. The pyperclip module does not come with Python. To install it, use below command pip install pyperclip
  88. 88. import pyperclip pyperclip.copy('Hello, world!') pyperclip.paste() Of course, if something outside of your program changes the clipboard contents, the paste() function will return it. For example, if I copied this sentence to the clipboard and then called paste(), it would look like this: >>> pyperclip.paste() 'For example, if I copied this sentence to the clipboard and then called paste(), it would look like this:'
  89. 89. String Methods Python has a set of built-in methods that you can use on strings. Note: All string methods return new values. They do not change the original string. Method Description capitalize() Converts the first character to upper case casefold() Converts string into lower case center() Returns a centered string count() Returns the number of times a specified value occurs in a string encode() Returns an encoded version of the string endswith() Returns true if the string ends with the specified value expandtabs() Sets the tab size of the string find() Searches the string for a specified value and returns the position of where it was found format() Formats specified values in a string format_map() Formats specified values in a string index() Searches the string for a specified value and returns the position of where it was found
  90. 90. isalnum() Returns True if all characters in the string are alphanumeric isalpha() Returns True if all characters in the string are in the alphabet isdecimal() Returns True if all characters in the string are decimals isdigit() Returns True if all characters in the string are digits isidentifier() Returns True if the string is an identifier islower() Returns True if all characters in the string are lower case isnumeric() Returns True if all characters in the string are numeric isprintable() Returns True if all characters in the string are printable isspace() Returns True if all characters in the string are whitespaces istitle() Returns True if the string follows the rules of a title isupper() Returns True if all characters in the string are upper case join() Joins the elements of an iterable to the end of the string
  91. 91. ljust() Returns a left justified version of the string lower() Converts a string into lower case lstrip() Returns a left trim version of the string maketrans() Returns a translation table to be used in translations partition() Returns a tuple where the string is parted into three parts replace() Returns a string where a specified value is replaced with a specified value rfind() Searches the string for a specified value and returns the last position of where it was found rindex() Searches the string for a specified value and returns the last position of where it was found rjust() Returns a right justified version of the string rpartition() Returns a tuple where the string is parted into three parts
  92. 92. rsplit() Splits the string at the specified separator, and returns a list rstrip() Returns a right trim version of the string split() Splits the string at the specified separator, and returns a list splitlines() Splits the string at line breaks and returns a list startswith() Returns true if the string starts with the specified value strip() Returns a trimmed version of the string swapcase() Swaps cases, lower case becomes upper case and vice versa title() Converts the first character of each word to upper case translate() Returns a translated string upper() Converts a string into upper case zfill() Fills the string with a specified number of 0 values at the beginning
  93. 93. Exercise: 1. Use the len method to print the length of the string. 2. Get the first character of the string txt. 3. Get the characters from index 2 to index 4 (llo). 4. Return the string without any whitespace at the beginning or the end. 5. Convert the value of txt to upper case. 6. Convert the value of txt to lower case. 7. Replace the character H with a J. 8. Insert the correct syntax to add a placeholder for the age parameter.

×