ESIT135 Problem Solving Using Python Notes of Unit-3
1.
Tuples: Tuple Basics,Operations, Methods, Packing and Unpacking, Tuple assignment, tuple as return value; Dictionaries: Dictionary Basics, Operations, Methods, Aliasing and Copying with Dictionaries, Nested Dictionaries Tuple: UNIT IV ADVANCED DATATYPES ❖ A tuple is same as list, except that the set of elements is enclosed in parentheses instead of square brackets. ❖ A tuple is an immutable list. i.e. once a tuple has been created, you can't add elements to a tuple or remove elements from the tuple. ❖ But tuple can be converted into list and list can be converted in to tuple. methods example description list( ) >>> a=(1,2,3,4,5) >>> a=list(a) >>> print(a) [1, 2, 3, 4, 5] it convert the given tuple into list. tuple( ) >>> a=[1,2,3,4,5] >>> a=tuple(a) >>> print(a) (1, 2, 3, 4, 5) it convert the given list into tuple. Benefit of Tuple: ❖ Tuples are faster than lists. ❖ If the user wants to protect the data from accidental changes, tuple can be used. ❖ Tuples can be used as keys in dictionaries, while lists can't. Operations on Tuples: 1. Indexing 2. Slicing 3. Concatenation 4. Repetitions 5. Membership 6. Comparison
2.
Operations examples description Creatinga tuple >>>a=(20,40,60,”apple”,”ball”) Creating the tuple with elements of different data types. Indexing >>>print(a[0]) 20 >>> a[2] 60 Accessing the item in the position 0 Accessing the item in the position 2 Slicing >>>print(a[1:3]) (40,60) Displaying items from 1st till 2nd. Concatenation >>> b=(2,4) >>>print(a+b) >>>(20,40,60,”apple”,”ball”,2,4) Adding tuple elements at the end of another tuple elements Repetition >>>print(b*2) >>>(2,4,2,4) repeating the tuple in n no of times Membership >>> a=(2,3,4,5,6,7,8,9,10) >>> 5 in a True >>> 100 in a False >>> 2 not in a False Returns True if element is present in tuple. Otherwise returns false. Comparison >>> a=(2,3,4,5,6,7,8,9,10) >>>b=(2,3,4) >>> a==b False >>> a!=b True Returns True if all elements in both elements are same. Otherwise returns false Tuple methods: ❖ Tuple is immutable so changes cannot be done on the elements of a tuple once it is assigned. methods example description a.index(tuple) >>> a=(1,2,3,4,5) >>> a.index(5) 4 Returns the index of the first matched item. a.count(tuple) >>>a=(1,2,3,4,5) >>> a.count(3) 1 Returns the count of the given element.
3.
Tuple Assignment: >>>(a,b,c)=(1,2,3) >>>print(a) 1 >>>print(b) 2 >>>print(c) 3 Tuple asreturn value: len(tuple) >>> len(a) 5 return the length of the tuple min(tuple) >>> min(a) 1 return the minimum element in a tuple max(tuple) >>> max(a) 5 return the maximum element in a tuple del(tuple) >>> del(a) Delete the entire tuple. ❖ Tuple assignment allows, variables on the left of an assignment operator and values of tuple on the right of the assignment operator. ❖ Multiple assignment works by creating a tuple of expressions from the right hand side, and a tuple of targets from the left, and then matching each expression to a target. ❖ Because multiple assignments use tuples to work, it is often termed tuple assignment. Uses of Tuple assignment: ❖ It is often useful to swap the values of two variables. Example: Swapping using temporary variable: Swapping using tuple assignment: a=20 b=50 temp = a a = b b = temp print("value after swapping is",a,b) a=20 b=50 (a,b)=(b,a) print("value after swapping is",a,b) Multiple assignments: Multiple values can be assigned to multiple variables using tuple assignment. ❖ A Tuple is a comma separated sequence of items. ❖ It is created with or without ( ).
4.
Dictionaries: ❖ A functioncan return one value. if you want to return more than one value from a function. we can use tuple as return value. Example1: Output: def div(a,b): r=a%b q=a//b return(r,q) a=eval(input("enter a value:")) b=eval(input("enter b value:")) r,q=div(a,b) print("reminder:",r) print("quotient:",q) enter a value:4 enter b value:3 reminder: 1 quotient: 1 Example2: Output: def min_max(a): small=min(a) big=max(a) return(small,big) a=[1,2,3,4,6] small,big=min_max(a) print("smallest:",small) print("biggest:",big) smallest: 1 biggest: 6 Tuple as argument: ❖ The parameter name that begins with * gathers argument into a tuple. Example: Output: def printall(*args): print(args) printall(2,3,'a') (2, 3, 'a') ❖ Dictionary is an unordered collection of elements. An element in dictionary has a key: value pair. ❖ All elements in dictionary are placed inside the curly braces i.e. { } ❖ Elements in Dictionaries are accessed via keys and not by their position. ❖ The values of a dictionary can be any data type. ❖ Keys must be immutable data type (numbers, strings, tuple) Operations on dictionary: 1. Accessing an element 2. Update
5.
Methods in dictionary: 3.Add element 4. Membership Operations Example Description Creating a dictionary >>> a={1:"one",2:"two"} >>> print(a) {1: 'one', 2: 'two'} Creating the dictionary with elements of different data types. accessing an element >>> a[1] 'one' >>> a[0] KeyError: 0 Accessing the elements by using keys. Update >>> a[1]="ONE" >>> print(a) {1: 'ONE', 2: 'two'} Assigning a new value to key. It replaces the old value by new value. add element >>> a[3]="three" >>> print(a) {1: 'ONE', 2: 'two', 3: 'three'} Add new element in to the dictionary with key. membership a={1: 'ONE', 2: 'two', 3: 'three'} >>> 1 in a True >>> 3 not in a False Returns True if the key is present in dictionary. Otherwise returns false. Method Example Description a.copy( ) a={1: 'ONE', 2: 'two', 3: 'three'} >>> b=a.copy() >>> print(b) {1: 'ONE', 2: 'two', 3: 'three'} It returns copy of the dictionary. here copy of dictionary ’a’ get stored in to dictionary ‘b’ a.items() >>> a.items() dict_items([(1, 'ONE'), (2, 'two'), (3, 'three')]) Return a new view of the dictionary's items. It displays a list of dictionary’s (key, value) tuple pairs. a.keys() >>> a.keys() dict_keys([1, 2, 3]) It displays list of keys in a dictionary a.values() >>> a.values() dict_values(['ONE', 'two', 'three']) It displays list of values in dictionary
6.
a.pop(key) >>> a.pop(3) 'three' >>>print(a) {1: 'ONE', 2: 'two'} Remove the element with key and return its value from the dictionary. setdefault(key,value) >>> a.setdefault(3,"three") 'three' >>> print(a) {1: 'ONE', 2: 'two', 3: 'three'} >>> a.setdefault(2) 'two' If key is in the dictionary, return its value. If key is not present, insert key with a value of dictionary and return dictionary. a.update(dictionary) >>> b={4:"four"} >>> a.update(b) >>> print(a) {1: 'ONE', 2: 'two', 3: 'three', 4: 'four'} It will add the dictionary with the existing dictionary fromkeys() >>> key={"apple","ball"} >>> value="for kids" >>> d=dict.fromkeys(key,value) >>> print(d) {'apple': 'for kids', 'ball': 'for kids'} It creates a dictionary from key and values. len(a) a={1: 'ONE', 2: 'two', 3: 'three'} >>>lena(a) 3 It returns the length of the list. clear() a={1: 'ONE', 2: 'two', 3: 'three'} >>>a.clear() >>>print(a) >>>{ } Remove all elements form the dictionary. del(a) a={1: 'ONE', 2: 'two', 3: 'three'} >>> del(a) It will delete the entire dictionary. Aliasing(copying)in Dictionary: ❖ Creating a copy of a dictionary is called aliasing. When you create a copy, both dictionary will be having same memory location. ❖ Changes in one dictionary will affect another dictionary. ❖ Aliasing refers to having different names for same dictionary values.
7.
❖ In thisa single dictionary object is created and modified using the subscript operator. ❖ When the first element of the dictionary named “a” is replaced, the first element of the dictionary named “b” is also replaced. ❖ This type of change is what is known as a side effect. This happens because after the assignment b=a, the variables a and b refer to the exact same dictionary object. ❖ They are aliases for the same object. This phenomenon is known as aliasing. ❖ To prevent aliasing, a new object can be created and the contents of the original can be copied which is called cloning. Cloning: ❖ To avoid the disadvantages of copying we are using cloning. ❖ Creating a copy of a same dictionary of elements with two different memory locations is called cloning. ❖ Changes in one dictionary will not affect locations of another dictionary. ❖ Cloning is a process of making a copy of the dictionary without modifying the
8.
original dictionary. ❖ Indictionary we can use copy() method for cloning. ❖ Slicing is not supported in the dictionary to reduce aliasing effect. Difference between List, Tuples and dictionary: List Tuples Dictionary A list is mutable A tuple is immutable A dictionary is mutable Lists are dynamic Tuples are fixed size in nature In values can be of any data type and can repeat, keys must be of immutable type List are enclosed in brackets[ ] and their elements and size can be changed Tuples are enclosed in parenthesis ( ) and cannot be updated Tuples are enclosed in curly braces { } and consist of key:value Homogenous Heterogeneous Homogenous Example: List = [10, 12, 15] Example: Words = ("spam", "egss") Or Words = "spam", "eggs" Example: Dict = {"ram": 26, "abi": 24} Access: print(list[0]) Access: print(words[0]) Access: print(dict["ram"])
9.
Can contain duplicate elements Cancontain duplicate elements. Faster compared to lists Cant contain duplicate keys, but can contain duplicate values Slicing can be done Slicing can be done Slicing can't be done Usage: ❖ List is used if a collection of data that doesnt need random access. ❖ List is used when data can be modified frequently Usage: ❖ Tuple can be used when data cannot be changed. ❖ A tuple is used in combination with a dictionary i.e.a tuple might represent a key. Usage: ❖ Dictionary is used when a logical association between key:value pair. ❖ When in need of fast lookup for data, based on a custom key. ❖ Dictionary is used when data is being constantly modified.