0% found this document useful (0 votes)
29 views

Python Programming Lab PDF For College

Python programming

Uploaded by

jashuj885
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
29 views

Python Programming Lab PDF For College

Python programming

Uploaded by

jashuj885
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 16
mm 2, TUPLES hon, In Python, a tuple is c A tuple is a collection of ordered, immutable elements in pytl defined using parentheses, ( ), and the elements are separate contain elements of different data types, including integers, floats, stv d by commas. Tuples can ings, and other objects. of elements or items. Tuples are A Tuple is a python sequence which stores a group utable whereas lists are mutable similar to lists but the main difference is tuples are immt Once we create a tuple we cannot modify its elements. Hence, we cannot perform operations like append), extend(), insert(), remove(), pop() and clear() on tuples. Tuples are generally used to store data which should not be modified and retrieve that data on demand. Creating Tuples : We can create a tuple by writing elements separated by commas inside parentheses(). The elements can be same datatype or different types. To create an empty tuple, we can simply write empty parenthesis, as: tup=() To create a tuple with only one element, we can, mention that element in parenthesis and after that a comma is needed. In the absence of comma, python treats the element as int datatype. tup = (10) tup = (10,) print(tup) # display 10 print type(tup) # display print(tup) # display 10 print type(tup) # display (i) (iii) To create a tuple with different types of element tup = (10, 20, 31.5, Hydorabad) not mention any brackets and write the elements separating them by comma, then they are taken by default as a tuple. Ifwe do tup= 10, 20, 34, 47 It is possible to create a tuple from a list. This is done by converting a list into a tuple using tuple function. n=[1,2,3,4] #n is list tp=tuple(n) print(tp) # display ( 4) Another way to create a tuple by using range( ) function that returns a sequence. ‘ttuple(range(2,11,2)) print(t) # display (2,4,6,8,10) Accessing the tuple elements : Accessing the elements from a tuple can be done using indexing or slicing. This is same as that of a list. Indexing represents the position number of the element in the tuple. The position starts from 0. tup=(50,60,70,80,90) print(tup[0}) # display 50 print(tup[1:4]) # display (60,70,80) print(tup[-1]) # display 90 print(tup[-1:-4:-1]) # display (90,80,70) print(tup[-4:-1]) # display (60,70,80) Updating Tuples : Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example. tupt = (12, 34.56); tup2 = (‘abe ‘xyz'); # Following action is not valid for tuples # tup1[0] = 100; # So let's create a new tuple as follows tup3 = tup1 + tup2; print(tup3) ere min weeaow (iv) Delete Tuple EX nn SSID SEARS Sit a be ee When the above code is executed, It produces the following result * (12, 34.56, ‘abe’, xyz’) jements : Removing individual tuple elements Is not possible. There js, of course, nothing wrong with putting together another tuple with the undesired element, discarded, To explicitly remove an entire tuple, just use the del statement. For example : tup = (‘physics’, ‘chemistry’, 1997, 2000); print(tup) del tup; print(“After deleting tup : *) print(tup) This produces the following result. Note an exception raised, this is because after del tup tuple does not exist anymore (physics’, ‘chemistry’, 1997, 2000) After deleting tup : NameError: name ‘tup’ is not defined (v) Compare tuple elements : To compare tuple elements, you can use the comparison operators (<, >, >=, = !=). When comparing tuples, Python compares the elements Pair wise starting from the first element of each tuple. If the elements at the same Position in both tuples are equal, Python moves on to the next elements and continues the comparison until it finds a mismatch or reaches the end of both tuples. Here’s an example: tuplet = (1, 2, 3) tuple2 = (1, 2, 4) if tuplet < tuple2: print("tuple1 is less than tuple2") elif tuple1 > tuple2: print(‘tuple1 is greater than tuple2") else: print(“tuple1 and tuple2 are equal") In the above code, python compares the first element of tuple] and tuple2, which are both equal to 1. Then it moves on to the second element, which is also equal in both tuples. Finally, it compares the third element, and finds that tuple2 has a larger element at that position, Therefore, the code outputs “tuple1 is less than tuple2”, WARNING ; XEROX / PHOTOCOPYING OF THIS BOOK Is 1LLEGAL = Nts BASICS OF PYTHON PROGRAMING Ea ee Operations on Tuple [Operatio ere eeenl Deseription Fen Retum the length of tuple. - Luplmp2 —Coneaten _ _ | Tup*n Peon ti values ' inn number of times, a [xin up Return True ifx is found in tuple otherwise returns False. emp(tup!, tup2) Compare elements of both tuples, | max(wp) Returns the maximum value in tuple. (_min(tup) Retums the minimum value in tuple. | tupledlist) Convert list into tuple, |Ltup.count(x) | Returns how many times the element ‘x’ is foudn in tuple. | | tup.index(x) Retums the first occurrence ofthe element ‘x’ in tuple. | | Raises ValueError if ‘x’ is not found in the tuple. | sorted(tup) 1 Sorts the elements of tuple into ascending order. Sorted(tup, reverse=True) will sort in reverse order. a Nested Tuples : Python allows you to define a tuple inside another tuple. This is called a nested tuple. students=((“RAVI”, “CSE”, 92.00), (“RAMU", “ECE”, 93.00), (“RAJA”, “EEE”, 87.00)) for iin students : print(i) Output : ('RAVI", "CSE", 92.00) (‘RAMU’, “ECE”, 93.00) (‘RAJA’, “EEE”, 87.00) Advantages of Tuples over Lists : Since, tuples are quite similar to lists, both of them are used in similar situations as well. However, there are certain advantages of implementing a tuple over a list. Below listed are some of the main advantages: 1. We generally use tuple for heterogeneous (different) datatypes and list for homogeneous (similar) datatypes. 2. Since tuples are immutable, iterating through tuple is faster than with list, So there is a slight performance boost, PT 3. Tuples that contain immutable elements can be used as keys for a dictionary With list, this is not possible. 4. If you have data that doesn't change, implementing it as tuple will guarantee tha, it remains write-protected. Ti 3. SETS Set is another data structure supported by python. Basically, sets are same as lists by; with a difference that sets are lists with no duplicate entries. Technically a set is mutable and an unordered collection of items. This means that we can easily add o, remove items from it. Creating a Set : A set is created by placing all the items (elements) inside curly braces {}, separated by comma or by using the built-in function set(). It can have any number of items and they may be of different types (integer, float, tuple, string etc.). fi Syntax : var2, var3, vard, # set of integers my_set = {1, 2, 3} print(my_set) # set of mixed datatypes my_set = {1.0, “Hello”, (1, 2, 3)} print(my_set) output : {1, 2, 3) {‘Hello’, 1.0, (1, 2, 3)} # set do not have duplicates my_set = {1, 2, 3, 4, 3, 2} print(my_set) # Output: (1, 2, 3, 4} (ii) Converting a list/tuple into Set : A set can have any number of items and they may be of different data types. set() function is used to converting list into set. s=set( [ 1, 2.5, “abo” ]) print(s) # display {1, 2.5, ‘abc’} (ili) (iv) (GYUDON TRU URAM MING» We can also convert tuple or string into set wp= (1,2.3,4,5) print(set(tup)) # {1, 2, 3, 4, 5) Creating an empty Set : Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements we use the set() function without any argument. Example : a=Q # check data type of a print(type(a)) # a =set() # check data type of a print(type(a)) # output : Update a Set : Sets are mutable. But since they are unordered, indexing have no meaning. We cannot access or change an element of set usii' indexing or slicing. Set does not support it. We can add single element using the addi) method and multiple elements using the update() method. The update() method can take tuples, lists, strings or other sets as its arguments. In all cases, duplicates are avoided. Example : # initialize my_set my_set = {1, 3} print(my_set) # Output: {1, 3} #my_set{0] _ # TypeError: ‘set’ object does not support indexing # add single element my_set.add(2) print(my_set) # Output: {1, 2, 3) # add multiple elements my_set.update([2,3,4]) Print(my_set) # Output: (1, 2, 3, 4} Example : # initialize A and B and C A={1,2,3, 4, 5} B= (4,5, 6, 7, 8) C= {10, 20, 30, 40} print(A | B) print(A.union(C)) Output : {1, 2, 3, 4, 5, 6, 7, 8} {1, 2, 3, 4, 5, 40,10, 20, 30} Set Intersection : Intersection of A and Bis a set of elements that are common in both sets. Intersection is performed using & operator. Same can be accomplished using the method intersection(). Example: # initialize A and B and c A={1, 2,3, 4, 5} B= (4,5, 6, 7, 8} C={2, 3, 10, 20} # use & operator print(A & B) print(A.intersection(C)) Set Difference: Difference of A and B(A- not in B. Similarly, (A - B) is a set of elements that are only in A but B - Aisa set of element in B but not in A. Difference is performed using - 0, difference(). 'Perator. Same can be accomplished using the method Example : # initialize A and B A=(1, 2,3, 4, 5} B= {4, 5, 6,7, 8} # use - operator on A print(A - B) print(B - A) A.difference(B) Ontout: {1, 2, 3} {8, 6, 7} (1,2, 3) Set Symmetric Difference: Symmetric Difference of A and B is a set of elements in both A and B except those that are common in both. Symmetric difference is performed using , operator. Same can be accomplished using the method symmetric_difference(). Example: # initialize Aand B A={1, 2,3, 4, 5} # use * operator print(A * B) A.symmetric_difference(B) TRL, me es Output: {1, 2, 3, 6, 7, 8} {1, 2, 3, 6, 7, 8} Table : Operations on sets [sno Operation | st s==t Returns True if two sets are equivalent and returns False. sist Returns True if two sets are not equivalent and returns False. | s.union(t) (or) New set with elements from both s and ¢ sit s.intersection (1) (or) ‘New set with elements common to s and t s&t — Tian aaiorence © s-t i | “a1. | ssymmetric_difference (1) | co) New set with elements in either s and ¢ but not both | f sAt _ | [12 | | New set with a shallow copy ofs | 113._ | supdate (0 Retum set s with elements added from ¢ _ | 14._ | s.intersection_update(s) Return set keeping only elements also fount in ¢ 15. | sdifference_update(t) Return set s after removing elements found in t | | 16, | ssymmetric_difference_up | Return sets after elements from s or ¢ but not both date(t) 17._ | s.add(x) Add element x to set s | 18._ | sremove(x) Remove x from sets; raises KeyError if not present | 19._| s.discard(x) Removes x from set s if present | 20. | spop0 Remove and retumn an arbitary element from s; | | raises KeyError if empty 21, | s.clear : Remove all elements form set s 22,__| max (s) Returns Maximum value in a set 23._| min(s) Returns Minimum value in a set 24, | Sorted (s) Return a new sorted list from the elements in the set. | Dictionaries : A dictionary represents a group of elements arranged in the form of key-value pairs. The first element is considered as ‘key’ and the immediate next element is taken as its ‘value’. The key and its value are separated by a colon (:). All the key- value pairs in a dictionary are inserted in curly braces { }. Dictionaries are sometimes found in other languages as “associative arrays” or “hashes”. Syntax : Dict-name={ key-1:val- key-2:val-2, ..Key-nval-n} Ex: d= { 'Regd.No’: 556, ‘Nami uresh’, ‘Branch’: ‘CSE’ } Here, the name of dictionary is ‘d’. The first element in the dictionary is a string ‘Regd.No’. So, this is called ‘key’. The second element is 556 which is taken as its ‘value’. should not use indexing oF slicing . perrol gl, acces the val, de the square braces, . re there ina dictions, we ‘assions will IV name insi a dictionary. etc. exPr n mention the how many ke key To acces y-value paits 2 example, dic associated with dict('Name'l- If we can use the d.No': 556, oan existing dictionary. This is done p, new nd assigning a valu also insert 4 'CSE'} ‘ranch’: ‘CSE} We can mentioning the key al "Name": 6, ‘Name’: ‘Suresh’ def Regd.No':556, “guresh’,"Branch': print(d) #(°Regd.NO": 55 fe’, ‘Gender: ‘Male') a[Gender}="Male" ", Branch’: ‘CS ‘Name’: ‘Suresh’ key-value pair from the di print(d) # {‘Regd.No': 556, Suppose, we want to delete a statement as: (del d['Regd.No'] # {Ni “Branch’: ‘CSE’, ‘Gender’ ame’: ‘Suresh’, ictionary, we can use de “Male e can use ‘in’ and ‘notin To Test whether a ‘key’ is available in a dictionary or not, w ese operators return either True oF False. operators. Thi a key ind and returns True / False Fame’ in d # check if ‘Nam‘ datatypes for value. For example, a value can be e rules: a number, string, lis. We can use any tuple or another dictionary. But keys should obey th duplicate keys are not allowed. If we enter * Keys should be unique. It means, n and only the new key will be same key again, the old key will be overwritte available. emp=(nag’:10,'vishnu’:20,'nag':20} print(emp) # {‘nag’: 20, ‘vishnu’: 20) THis BOOK IS ILLE emp=({'na9'}:10,"vishnu'20,;nag20) Traceback (most recent call last): File “", emp={[" line 4, in '7ag']:10,'vishnu’:20,'nag':20} TypeError: unhashable type: ‘list’ (i) Accessing value from Dictionar with key to obtain its value, Ex: ¥ : To access value in dictionary, [ ] are used along ‘name’: ‘ram’, ‘roll no’: ‘576, ‘course’ print(d[‘name'}) ‘Ouput : ram (ii) Adding items in Dictionary : Syntax: \dict-name[key]=value| d{'age']=20 print(d) Output: { ‘name’: ‘ram’, ‘roll no’: ‘576’, ‘course’: ‘b.tech’, ‘age’: 20} . (iii) Modifying items in dictionary : Ex: d['course']="m.tech’ print(d) Output : (‘name’: ‘ram’ , roll no’: ‘576, ‘course’: ‘m.tech’, ‘age’: 20) (iv) Deleting items in dictionary : Syntax: del Dict-name{key] del d['roll no’) print(d) Output: (name’: ‘ram’, ‘course’: ‘m.tech’, ‘age’: 20) ictionary based on keys of a dictionary (v) Sorting items in dictionary : To sort items in a dic Ex: print(sorted(d.keys())) print(d) : Output: {‘age’: 20, ‘course’: ‘m.tech’, ‘name’: ‘ram ; i nly value: (vi) Iterating using dictionary : We are iterating in a dictionary over keys, only °S Or using keys and values. Ex: d={‘name’: ‘ram’, ‘branch’: ‘ese’, ‘age’:20} for key in d.keys( print(key, en print() for value in d.values(): print(value, end=" *) print() for key,value in d.items(): print(key,value,end=" ‘) Output: name branch age ram cse 20 fname ram branch ese age 20 (vii) Nested dictionary : Maintaining one dictionary inside another dictionary. Ex: students={‘arjun’: {'ds": ‘80','c++': ‘75'},'arnav':{‘ds': '85','c++': ‘90'}} for key, val in students.items(): print(key,val) Output: (‘arjun’, {'ds’: ‘80','c+- (arnay’,{‘ds’: '85','c+- here is shother way to create dictionary syntax: 7 ——— getexpression for variable in Soquencotit condition}) | Ex: gefvex"'3 for x in range(1,6)) print(d) _ AGA IDE FOatput : (1:1, 28, 3:27, 4:64, 5:125) [outers x) Using for loop with Dictionaries : for loop is very convenient to retrieve the elements of dictionary. Let's take a simple dictionary that contains color code and its name as ‘RED’, ‘g':"GREEN’, ‘b BLUE", colors = ‘W':"WHITE" } Here, '’, ‘g', 'b',w represents keys and ‘RED’, ‘GREEN’, ‘BLUE" and ‘WHITE’ indicate values. colors = {'r'"RED", for k in colors: GREEN’, 'b':"BLUE’, ‘w'"WHITE” } print(kend=" *) # displays only keys print() for k in colors: print(colors[k],end=" *) # keys to to dictionary and display the values (x) Converting Lists into Dictionary : When we have two lists, it is possible to convert them into a dictionary. For example, we have two lists containing names of countries and names of their capital cities. There are two steps involved to convert the lists into a dictionary. The first step is to create a ‘zip’ class object by passing the two lists to zip( ) function. The zip( ) function is useful to convert the sequences into a zip class object. The second step is to convert the zip object into a dictionary by using dict() function. Example : ‘USA, ‘INDIA’, ‘GERMANY’, ‘FRANCE’ ] ‘Washington’, ‘New Delhi’, ‘Berlin’, ‘Paris’ ] countrie: cities = z=zip(countries, cities) d=dict(z) Print(d) Output : {'USA’: ‘Washington’, ‘INDIA’: ‘New Delhi’, ‘GERMANY’: ‘Berlin’, ‘FRANCE’: ‘Paris’} a NEROX PHOTOCORNG ORTH wOOKIs WLEOAL PEE i [RE Built-in Functions with Dictionary Built-in functions like all(), any(), len(), emp(), sorted() etc. dictionary to perform different | tasks. are commonly used ya, Function — Description , | all) Return True if all keys of the dictionary are true (or if the dictionary is empty), F any) Retum True if any key of the dictionary is true. If the dictionary is empty, retur, I False. - | tend) Return the length (the number of items) in the dictionary. > |_emp() Compares items of two dictionaries. | |_sorted() Return a new sorted list of keys in the dictionary. Different Methods of Dictionaries : Method Description —_ e | clear() Remove all items from the dictionary. | copy() Return a shallow copy of the dictionary. | fromkeys(seql, v)) Return a new dictionary with keys from seq and value equal to y (defaults to None). get(Keyl,dl) Return the value of key. If key does not exit, return d (defaults to Non) items() Return a new view of the dictionary’s items (key, value). _| keys() Return a new view of the dictionary’s keys. pop(keyL,d]) Remove the item with key and return its value or d if key is not found If dis not provided and key is not found, raises KeyError. | popitem() Remove and return an arbitrary item (key, value). Raises KeyError if the dictionary is empty. | | setdefault(keyf,d]) If key is in the dictionary, return its value. If not, insert key witha | | value of d and return d (defaults to None). update({other]) Update the dictionary with the key/value pairs from other, overwriting existing keys. _| [_values() Return a new view of the dictionary's values | Q. Write a python program to create a dictionary and find the sum of values. d={'m1’:85,'m3": sum=0 ,'eng’:86,'c':91} for iin d.values(): sum+= print(sum) # 346 ERO / PHOTOCOPYING OF THIS BOOK IS ILLEGAUN ™ to create a dictionary with cricket players See es aa match, Also we are retrieving rune by entering neint(input("Enter How many players? *)) a for range(0,n): input("Enter Player name: *) veinput(“Enter score: “) dtkl=v print(d) nam put(“Enter name of player for score: *) print(‘The Score is",d[name}) Ouput = Enter How many players? 3 Enter Player name: “Sachin” Enter score: 98 Enter Player name: “Sehwag” Enter score: 91 Enter Player name: “Dhoni* Enter score: 95 {'Sehwag’: 91, ‘Sachin’: 98, ‘Dhoni’: 95} Enter name of player for score: “Sehwag” The Score is 91 v

You might also like