SlideShare a Scribd company logo
1 of 106
Download to read offline
UNIT-03:
DATA STRUCTURES IN PYTHON
[14 MARKS]
BY MS. A. V. WANKAR
4 DATA STRUCTURES IN PYTHON
1. List
2. Tuple
3. Set
4. Dictionary
LISTS
lists can be heterogeneous
• a = [„hello', „example', 100, 1234, 2*2]
Lists can be indexed and sliced:
• a[0]  „hello‟
• a[:2]  [„hello', 'example']
Lists can be manipulated
• a[2] = a[2] + 23
• a[0:2] = [1,12]
• a[0:0] = []
• len(a)  5
LIST VARIETIES
 It is possible to create a new list from another.
 Example:
 A=[1,34.5,’hello’,2+3j]
 B=A # copies all elements of A to B, both points to same list,
Changing one changes the other.
 It is possible to create a list of lists:
 Example:
 List 1= [2, 5, 3]
 List2=[1,34,6]
 List3=[List1,List2]
 Print(List3)#[[2,5,3],[1,34,6]]
LIST VARIETIES (CONT…)
 A list can be embedded in another list.
 Example:
 A=[1,2,3,4]
 B=[10,20,A,30]
 Print(B) # [10,20,[1,2,3,4],30]
 It is possible to unpack a list within a list using the *
operator.
 Example:
 A= [1, 2, 3,4]
 B=[10,20,*A,30]
 Print(B) # [10,20,1,2,3,4,30]
LIST METHODS
 append(x): append element x at the end of list & does
not return anything. i.e. None is returned
 Syntax: list. append (x)
 Example:
• # Adds List Element as value of List.
• List = ['Mathematics', 'chemistry', 1997, 2000]
• List.append(20544)
• print(List)#5
LIST METHODS
 extend(List2): append all items in List2 to list l, returns
None.
 Syntax: List1.extend(List2)
 Example:
•List1 = [1, 2, 3]
•List2 = [2, 3, 4, 5]
•# Add List2 to List1
•List1.extend(List2)
•print(List1)
•# Add List1 to List2 now
•List2.extend(List1)
•print(List2)
LIST METHODS
 insert(i, x): Insert element x at index i (i should be
within range , otherwise we get Index Error ), returns
None.
 Syntax: list.insert(index, x)
 Example:
•List = ['Mathematics', 'chemistry', 1997, 2000]
•# Insert at index 2 value 10087
•List.insert(2,10087)
•print(List)
LIST METHODS
 count(x): Returns total occurrence of element x in List
 Syntax: List.count(x)
 Example:
•List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
•print(List.count(1))
 index(x) : Returns the index of first occurrence of x
 Syntax: List.index(x[,start][,end])
 Example:
•List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
•print(List.index(2))
•Print(List.index(2,2))
•Print(List.index(2,5,9) # it will search in start=5 and end=9-1
LIST METHODS
 pop([index]) : Index is not a necessary parameter, if not
mentioned pops and returns element at the last index.
 Syntax: list.pop([index])
 Example:
 List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
 print(List.pop())
 print(List.pop(0))
 remove(x): remove first occurance of element x from list,
returns None.
 Syntax: list. remove(x)
 Example:
 List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
 List.remove(3)
 print(List)
LIST METHODS
 reverse(): It simply reverses the list, returns None.
 Syntax: List.reverse()
 Example:
 List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
 List.reverse()
 print(List)
 sort() : Sorts the list in Place
 Syntax: List.sort([key,[Reverse_flag]])
 Example:
 List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
 Print(List.sort())
 #Reverse flag is set True
 List.sort(reverse=True)
 print(List)
LIST METHODS
 clear(): It simply reverses the list, returns None.
 Syntax: List.clear()
 Example:
 List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
 List.clear()
 print(List)# prints empty list
 copy() : copy elements of List. Returns List
 Syntax: List.copy()
 Example:
 List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
 L=List.copy()
 print(L)
DELETING ELEMENT USING DEL
del list[index]: Element to be deleted is mentioned using list
name and index. remove by index, not value remove slices from
list (rather than by assigning an empty list)
 Syntax: del list[index] or del list[start_index : end_index]
 Example:
 List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
 del List[0]
 del List[3:5] # removes elements from index start to end-1
 Print(List)
BUILT-IN FUNCTIONS OF LIST
 sum() : Calculates & Returns sum of all the elements of List.
 Syntax: sum(List)
 Example:
 List = [1, 2, 3, 4, 5]
 print(sum(List))
 Note: Sum is calculated only for Numeric values, elsewise
throws TypeError.
 len() :Calculates & Returns total length of List.
 Syntax: len(list_name)
 Example:
 List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
 print(len(List))
BUILT-IN FUNCTIONS OF LIST
 min() : Calculates & Returns minimum of all the elements of
List.
 Syntax: min(List)
 Example:
 List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
 print(min(List))
 max() :Calculates & Returns maximum of all the elements of
List.
 Syntax: max(List)
 Example:
 List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
 print(max(List))
BUILT-IN FUNCTIONS OF LIST
 sorted() : returns a sorted list of the specified list.
 Syntax: sorted(list[,key[, Reverse_Flag ] ])
 Example:
 List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
 l1=sorted(List)
 Print(l1)
 l2=sorted(List, reverse=True)
 Print(l2)
Note: if Reverse_Flag = True then sorts in descending order
otherwise sort in ascending order, by default Reverse_Flag = False.
USING ALL() BUILT-IN FUNCTIONS
 This function returns true if all of the items are True (or if
the iterable is empty).
 All can be thought of as a sequence of AND operations on the
provided iterables.
 Syntax: all(list of iterables)
 Example:
 # print (all([True, True, True, True])) # Here all the iterables are
True so all will return True and the same will be printed
 print (all([False, True, True, False])) # False
 print (all([False, False, False])) # False
USING ANY() BUILT-IN FUNCTIONS
 Returns true if any of the items is True.
 It returns False if empty or all are false. Any can be thought
of as a sequence of OR operations on the provided iterables.
 Syntax: any(list of iterables)
 Example:
 # print (any([False, False, False, False])) # Here all the
iterables are False so any will return False and the same will
be printed
 print (any([False, True, False, False])) # True
 print (any([True, False, False, False])) # True
LIST COMPREHENSION
 A list comprehension offers an easy way of creating
lists.
 It consists of brackets containing expression followed
by a for clause, and zero or more for or if clause.
 Used when you want to create a new list based on the
values of an existing list.
 Syntax:
 Newlist = [expression for item in iterable/sequence [optional for
and/or if] ]
LIST COMPREHENSION (CONT.…)
 Example:
A = [0,5,6,3,2,9,8,4]
B=[]
for i in A:
 if i>=5:
 B.append(i)
print(B) # [5,6,9,8]
 Same can be done in One line using list comprehension
L=[x for x in A if x>=5]
print(L) # [5,6,9,8]
LIST COMPREHENSION (CONT.…)
>>> a = [2,4,6]
>>> [3*x for x in a]
[6, 12, 18]
>>> [{x: x**2} for x in a}
[{2: 4}, {4: 16}, {6: 36}]
>>> [[x, x**2] for x in a]
[[2, 4], [4, 16], [6, 36]]
>>> [[x, x**2] for x in a]
[[2, 4], [4, 16], [6, 36]]
LIST COMPREHENSION (CONT.…)
cross products:
>>> vec1 = [2,4,6]
>>> vec2 = [4,3,-9]
>>> [x*y for x in vec1 for y in vec2]
[8,6,-18, 16,12,-36, 24,18,-54]
>>> [ x+y for x in vec1 for y in vec2]
[6,5,-7,8,7,-5,10,9,-3]
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
[8,12,-54]
LIST COMPREHENSIONS
can also use if:
>>> [3*x for x in vec if x > 3]
[12, 18]
>>> [3*x for x in vec if x < 2]
[]
LIST COMPREHENSION (CONT.…)
>>> a = [(i, j) for i in [1,2] for j in [1,2] if i!=j]
>>>print(a)
[ (1,2),(2,1) ]
>>> a=[(i, j, k) for i in [1,2,3] for j in [1, 2, 3] for k in [1,
2, 3] if i!=j and j!=k and k!=i]
>>> print(a)
[(1,2,3), (1,3,2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
>>> arr=[[1,2,3,4], [5,6,7,8]]
>>>b=[n for ele in arr for n in ele]
>>>print(b)
[1,2,3,4,5,6,7,8]
TUPLES: INTRODUCTION
 A simple immutable ordered sequence of items.
 Items can be of mixed types, including
collection types.
 tuples are defined using parentheses and
commas.
 Example:
t = (23,„abc‟,4.56,(2,3),„xyz‟)
 individual members of a tuple are accessed by
using positive and negative index starting with
„0‟ similar to the lists.
 Example:
print(t[0]) # prints 23
print(t[-1]) # prints „xyz‟
TUPLES: DEFINING TUPLES
 Using parenthesis to define tuple is optional.
 Example:
a=10;b=20;c=30
t=a, b, c
or
t=(a, b, c)
print(t)
 Empty tuple can be created as shown below.
 Example:
t=()
print(t)#()
 A tuple with single value can be created as..
 Example:
t=(23,)
 Note: note the comma (,) written after 23. If we
don‟t give this comma then t will be created as a
normal variable instead of tuple.
TUPLES: UNPACKING
 It is possible to unpack tuples & also lists.
 Example:
a=t[0]
b=t[1]
c=t[2]
(a, b, c)=t
or
a, b, c=t
 If the number of variables are less than the
number of values then we can add an * to the
variable name and the values will be assigned
to the variable as a list:
 Example1:
t = (23,„abc‟,4.56,(2,3),„xyz‟)
(a, b, *c)=t
print(c)
TUPLES: UNPACK CONT..
 Example2:
t = (23,„abc‟,4.56,(2,3),„xyz‟)
(a, *b, c)=t
print(a)#23
Print(b)#[„abc‟,4.56,(2,3)]
print(c)#xyz
 It is possible to unpack tuple within another
tuple.
 Example:
t1=(100,*t)
print(t1) # (100,23,‟abc‟,4.56,(2,3),‟xyz‟)
TUPLES: SLICE/CUT OPERATOR ([:])
 We can use cut/slice operator ([:]) with tuples
similar to the lists.
 Example:
t=(23,45,56.4,3+6j,‟abc‟)
print(t[2:])#(56.4,3+6j,‟abc‟)
 We can print all elements of tuple using cut/slice
operator ([:]) similar to lists.
 Example:
t=(23,45,56.4,3+6j,‟abc‟)
print(t[:])#(23,45,56.4,3+6j,‟abc‟)
 Similar to the lists we can print tuple in a reverse
using cut/slice operator ([:])
 Example:
t=(23,45,56.4,3+6j,‟abc‟)
print(t[::-1])#(23,45,56.4,3+6j,‟abc‟)
TUPLE VARIETIES
 It is possible to create a new tuple from another.
 Example:
 A=(1,34.5,’hello’,2+3j)
 B=A # copies all elements of A to B, both points to same tuple.
 It is possible to create a tuple of tuple:
 Example:
 t1= (2, 5, 3)
 t2=(1,34,6)
 t3=(t1, t2)
 print(t3)#((2,5,3),(1,34,6))
LIST VARIETIES (CONT…)
 A tuple can be embedded in another tuple.
 Example:
 A=(1,2,3,4)
 B=(10,20,A,30)
 print(B) # (10,20,(1,2,3,4),30)
 Similar to lists, it is possible to concatenate two tuples.
 Example:
 A= (1, 2, 3,4)
 B=(10,20,30)
 C=A+B
 print(C) # (1,2,3,4,10,20,30)
TUPLES: METHODS
 1. t.count() : the count() method returns the number of
times a specified value appears in the tuple.
 Syntax:
t.count(value)# value is nothing but item to search
for in tuple t.
 Example:
t=(23,45,23,56.4,3+6j,‟abc‟)
print(t.count(23))#2
 2. t.index() : Search for the first occurrence of the value 8,
and return its position.
 Syntax:
t.index(value)# value is nothing but item to search
for in tuple t.
 Example:
t=(23,45,23,56.4,3+6j,‟abc‟)
print(t.index(23))#0
TUPLES: BUILT-IN FUNCTIONS
 1. t.count() : the count() method returns the number of
times a specified value appears in the tuple.
 Syntax:
t.count(value)# value is nothing but item to search
for in tuple t.
 Example:
t=(23,45,23,56.4,3+6j,‟abc‟)
print(t.count(23))#2
 2. t.index() : Search for the first occurrence of the value 8,
and return its position.
 Syntax:
t.index(value)# value is nothing but item to search
for in tuple t.
 Example:
t=(23,45,23,56.4,3+6j,‟abc‟)
print(t.index(23))#0
BUILT-IN FUNCTIONS OF TUPLE
 sum() : Calculates & Returns sum of all the elements of
tuple.
 Syntax: sum(t)
 Example:
 t = (1, 2, 3, 4, 5)
 print(sum(t))
 Note: Sum is calculated only for Numeric values, elsewise
throws TypeError.
 len() :Calculates & Returns total length of tuple.
 Syntax: len(tuple_name)
 Example:
 t = (1, 2, 3, 1, 2, 1, 2, 3, 2, 1)
 print(len(t))
BUILT-IN FUNCTIONS OF TUPLE
 min() : Calculates & Returns minimum of all the elements of
tuple.
 Syntax: min(t)
 Example:
 t = (2.3, 4.445, 3, 5.33, 1.054, 2.5)
 print(min(t))
 max() :Calculates & Returns maximum of all the elements of
tuple.
 Syntax: max(t)
 Example:
 t = (1, 2, 3, 1, 2, 1, 2, 3, 2, 1)
 print(max(t))
BUILT-IN FUNCTIONS OF TUPLE
 sorted() : returns a sorted list of the specified tuple.
 Syntax: sorted(tuple_name[,key[, Reverse_Flag ] ])
 Example:
 t= [2.3, 4.445, 3, 5.33, 1.054, 2.5]
 l1=sorted(t)
 Print(l1)
 l2=sorted(List, reverse=True)
 Print(l2)
Note: if Reverse_Flag = True then sorts in descending order
otherwise sort in ascending order, by default Reverse_Flag = False.
USING ALL() BUILT-IN FUNCTIONS
 This function returns true if all of the items are True (or if
the iterable is empty).
 All can be thought of as a sequence of AND operations on the
provided iterables.
 Syntax: all(list of iterables)
 Example:
 # print (all((True, True, True, True))) # Here all the iterables are
True so all will return True and the same will be printed
 print (all((False, True, True, False))) # False
 print (all((False, False, False))) # False
USING ANY() BUILT-IN FUNCTIONS
 Returns true if any of the items is True.
 It returns False if empty or all are false. Any can be thought
of as a sequence of OR operations on the provided iterables.
 Syntax: any(list of iterables)
 Example:
 # print (any((False, False, False, False))) # Here all the
iterables are False so any will return False and the same will
be printed
 print (any((False, True, False, False))) # True
 print (any((True, False, False, False))) # True
USING ZIP() BUILT-IN FUNCTIONS
 The zip() function returns a zip object, which is an
iterator of tuples where the first item in each passed
iterator is paired together, and then the second item in
each passed iterator are paired together and so on …..
 Syntax: zip(*iterables) # can be anything like lists,
tuples etc.
 If we do not pass any parameter, zip() returns an empty
iterator.
 If a single iterable is passed, zip() returns an iterator of
tuples with each tuple having only one element.
 If the passed iterators have different lengths, the
iterator with the least items decides the length of the
new iterator.
USING ZIP() BUILT-IN FUNCTIONS
 Example1:
a=zip()
b=list(a)
print(b)#[]
 Example2:
number_list = [1, 2, 3]
str_list = ['one', 'two', 'three']
Result=zip(number_list,str_list)
R=list(Result)
print(R)
UNZIPPING THE ZIPPED LIST
 The * operator can be used in conjunction with zip() to
unzip the list. a=zip()
Example:
number_list = [1, 2, 3]
str_list = ['one', 'two', 'three']
Result=zip(number_list,str_list)
R=tuple(Result)
num, str=zip(*R)
print(num)
print(str)
PROBLEM STATEMENT: 01
 Create 3 lists – a list of names, a list of ages, a list
of salaries. Generate and print a list of tuples
containing name, age and salary from the 3 lists.
From this list generate 3 tuples – one containing
all names, another containing all ages and third
containing all salaries.
ANSWER:
names_list=[„abc‟,‟xyz‟,‟pqr‟]
ages_list=[23,45,32]
salaries_list=[2300,8600,6700]
l=list(zip(names, ages, salaries)]
print(l)
name_tuple, age_tuple, salary_tuple=zip(*l)
print(name_tuple)
print(age_tuple)
print(salary_tuple)
PROBLEM STATEMENT: 02
 Create a list of tuples. Each tuple should contain
an item and its price in float. Write a program to
sort the tuples in descending order by price.
USING DIVMOD() BUILT-IN FUNCTION
 divmod() function takes two argument and return
the tuple of quotient and the reminder.
 Example1:
Result=divmod(17,3)
print(Result)
 Example2:
t=(17,3)
R=divmod(*t)
print(R)
PRACTICE QUESTIONS:
a) Write a program to obtain transpose of a 3x4
matrix using zip().
b) Write a program to multiply two matrices x(2x3)
and y(2x2) using list comprehension and zip
function.
c) Suppose we have a list of 5 integers and a tuple of
5 floats. Can we zip them and obtain an iterator.
If yes, how ?
d) Write a program to unzip a list of tuples into
individual lists
e) Suppose a date is represented as a tuple (d, m, y).
Write a program to create 2 date tuples and find
the number of days between the two dates.
ASSIGNMENT NO: 03
Store the data about shares held by a user as tuples
containing the following information about shares.
Share name
Date of purchase
Cost price
Number of shares
Selling price
Write a program to determine:
a) Total cost of portfolio
b) Total amount gained or lost.
c) Percentage profit made or loss incurred.
SET IN PYTHON: INTRODUCTION
 A set is an unordered collection of items which are
separated by comma (,) and enclosed in curly
brackets ({ }).
 Items of a set can be of any data type.
 set do not contain duplicate values
 Example:
A={20} # set with 1 value.
B={„abc‟,34,7+3j,90.45} # set with multiple items.
C={10,10,10,10} # only 1 10 gets stored.
SET IN PYTHON: INTRODUCTION (CONT…)
 Set is an unordered collection, hence order of
insertion is not same as the order of access.
 Example:
A={15,25,35,45,55}
print(A) # doesn‟t always print {15,25,35,45,55}
 The elements in the set are immutable(cannot be
modified) but the set as a whole is mutable i.e. We
can add or remove items from it.
SET IN PYTHON: INTRODUCTION (CONT…)
 A set() function can be used to convert a string, ,
list or tuple into a set.
 Example:
L=[10,20,30,40,50]
T=(„abc‟, 25, 32.435)
S=„Programming‟
S1=set(L) #{30, 20, 10, 40, 50}
S2=set(T) # {„abc‟, 32.435, 25}
S3=set(S) #{„P‟, ‟r‟, „g‟, „o‟, „m‟, „n‟,‟g‟ }
 Note: While creating set using set(), repetitions are
eliminated.
CREATING EMPTY SET
 Empty set can be created by using a set()
constructor.
 Example:
S={} # It will create empty dictionary
S=set() # It will create empty set
 Note: It is not possible to create empty set by
using {} , instead it creates empty dictionary. To
create empty set, we must use set() constructor.
ACCESSING SET ELEMENTS:
 Being an unordered collection, items in a set
cannot be accessed using indices.
 Sets can not be sliced using [].
 Entire set can be printed by just using the name of
the set.
 Example:
S={10, 20, 30, 40, 50} #{30, 20, 10, 40, 50}
 Like strings, lists and tuples, sets can be iterated
over using a for loop.
 Example:
S={10, 20, 30, 40, 50}
for i in S:
print(i)
SET OPERATIONS:
 1) creating sets
Example:
S={10, 20, 30, 40, 50} #{30, 20, 10, 40, 50}
 We can use membership operator with set as
Example:
S={10, 20, 30, 40, 50}
print(12 in S) # False
print(12 not in S) # True
 Set can be deleted by using del keyword
Example:
S={10, 20, 30, 40, 50}
del S
print(S) # NameError
SET OPERATIONS: (CONT…)
 It is possible to unpack a set within using *.
Example:
S={10, 20, 30, 40, 50} #{30, 20, 10, 40, 50}
S1={100,*S,200}
print(*S1)
 A set can not contain a set embedded in it.
 Sets can also be used to perform mathematical set
operations like union, intersection, symmetric
difference, etc.
BUILT-IN FUNCTIONS OF SET
 sum() : Calculates & Returns sum of all the elements of set.
 Syntax: sum(s)
 Example:
 s= {1, 2, 3, 4, 5}
 print(sum(s))
 Note: Sum is calculated only for Numeric values, elsewise
throws TypeError.
 len() :Calculates & Returns number of items in a set.
 Syntax: len(s)
 Example:
 s= {1, 2, 3, 1, 2, 1, 2, 3, 2, 1}
 print(len(s))
BUILT-IN FUNCTIONS OF SET
 min() : Calculates & Returns minimum of all the elements of
set.
 Syntax: min(s)
 Example:
 s = {2.3, 4.445, 3, 5.33, 1.054, 2.5}
 print(min(s))
 max() :Calculates & Returns maximum of all the elements of
set.
 Syntax: max(s)
 Example:
 s= {1, 2, 3, 1, 2, 1, 2, 3, 2, 1}
 print(max(s))
BUILT-IN FUNCTIONS OF SET
 sorted() : returns a sorted list of the specified set.
 Syntax: sorted(set_name[,key[, Reverse_Flag ] ])
 Example:
 s = {2.3, 4.445, 3, 5.33, 1.054, 2.5}
 l1=sorted(s)
 print(l1)
 l2=sorted(s, reverse=True)
 print(l2)
Note: if Reverse_Flag = True then sorts in descending order
otherwise sort in ascending order, by default Reverse_Flag = False.
USING ALL() BUILT-IN FUNCTIONS
 This function returns true if all of the items are True (or if
the iterable is empty).
 All can be thought of as a sequence of AND operations on the
provided iterables.
 Syntax: all(s)
 Example:
 # print (all({True, True, True, True})) # Here all the iterables
are True so all will return True and the same will be printed
 print (all({False, True, True, False})) # False
 print (all({False, False, False})) # False
USING ANY() BUILT-IN FUNCTIONS
 Returns true if any of the items is True.
 It returns False if empty or all are false. Any can be thought
of as a sequence of OR operations on the provided iterables.
 Syntax: any(s)
 Example:
 # print (any({False, False, False, False})) # Here all the
iterables are False so any will return False and the same will
be printed
 print (any({False, True, False, False})) # True
 print (any({True, False, False, False})) # True
SET FUNCTIONS/METHODS
 add(ele):
 If we want to add a single element to an existing set, we can
use the .add() operation.
 It adds the element to the set and returns 'None'.
 If the element already exists then add() method do not add
an element.
 Syntax: s.add(ele) # adds element ele to set s
 Example:
S={10, 20, 89, 09}
S.add(100)
print(S) # {10, 89, 09, 100, 20}
S.add(10)
print(S) # {10, 89, 09, 100, 20}
SET FUNCTIONS/METHODS
 update(seq):
 If we want to add a sequence of items then we use it.
 seq can b a list, tuple , set or dictionary(If seq is dictionary
then only keys will be added to set & not values).
 It adds the elements of seq to the set and returns 'None'.
 If the elements of seq already exists then .update() method
do not add the elements.
 Syntax: s.update(seq) # adds elements of seq to set s
 Example:
S={10, 20, 89, 09}
S.update([100,200])
print(S) # {10, 89, 09, 100, 20}
S.update((12, 13))
print(S) # {10, 89, 09, 100, 20,13,12}
SET FUNCTIONS/METHODS
 clear():
 This method removes all elements of a set and return None.
 Syntax: s.clear() # removes all elements of set s
 Example:
S={10, 20, 89, 09}
S.clear()
print(S) # set()
print(s.clear()) # None
SET FUNCTIONS/METHODS
 remove(ele):
 This method removes element ele from the set.
 If element does not exist, it raises a KeyError.
 The method returns None.
 Syntax: s.remove(ele) # removes element ele of set s
 Example:
S={10, 20, 89, 09}
S.remove(20)
print(S) # {10, 89, 09}
print(s.remove(10)) # None
print(s.remove(20)) # KeyError is raised
SET FUNCTIONS/METHODS
 discard(ele):
 This method also removes element ele from the set.
 If element does not exist, it does not raise a KeyError.
The method returns None.
 Syntax: s.discard(ele) # removes element ele of set s
 Example:
S={10, 20, 89, 09}
S.discard(20)
print(S) # {10, 89, 09}
print(s.discard(10)) # None
print(s.discard(20)) # KeyError not raised
SET FUNCTIONS/METHODS
 pop():
 This operation removes and return an arbitrary element
from the set.
 If there are no elements to remove, it raises a KeyError.
 Syntax: s.pop() # removes arbitrary element of set s
 Example:
S={10, 20, 89, 09}
S.pop() # arbitrary element is popped and returned.
print(S) # arbitrary element which is popped
print(s.pop()) #
print(s.pop(20)) # KeyError raised
SET FUNCTIONS/METHODS
 copy():
 The copy() method returns a shallow copy of the set.
 A set can be copied using = operator in Python.
 Example:
S={2,35,79,0}
S1=S
print(S1)
S1.add(100)
print(S) # {35, 79, 0, 2, 100}
print(S1) # {35, 79, 0, 2, 100}
 Note: The problem with copying the set in this way is that if you modify the set S1,
the set S is also modified.
 Syntax: s.copy() # creates a shallow copy, changes made in shallow copy
do not change original set.
 Example:
S={10, 20, 89, 09}
S1=S.copy() #
print(S) #
print(S.copy()) #
print(s.pop(20)) # KeyError raised
SET FUNCTIONS/METHODS
 __len__():
This function returns length of the object.
Syntax: object.__len__()
Note: object can be a list, tuple, set or dictionary.
Example:
S={2,35,79,0}
print(S.__len__())
MATHEMATICAL OPERATIONS : UNION
 s1.union(s2) :
This method returns union of set and set of
elements in an iterable object s2.
Sometimes, the | operator is used in place
of union() method, but it operates only on the set of
elements in set.
Syntax: s1.union(s2)# here s2 can be set, list,
tuple, dictionary
or
s1|s2 # here s2 must be set only.
Example:
s1={0,1,2,6}
s2={34,54,6}
print(s1.union(s2)) #{0,54,34,6,1,2,6}
MORE EXAMPLES ON UNION
 s=set(“Hacker”)
 print(s.union(“Rank”))
 print(s.union([„R‟,‟a‟,‟n‟,‟k‟]))
 Print(s.union((„R‟,‟a‟,‟n‟,‟k‟)))
 Print(s.union({“Rank”:1}))
 Note: when we use dictionary as an argument to
union it will add key only in a union set.
 print(s|“Rank”)
 print(s|[„R‟, ‟a‟, ‟n‟, ‟k‟] )
 Print(s|(„R‟, ‟a‟, ‟n‟, ‟k‟))
 Print(s|{“Rank”:1})
 Print(s|{„R‟, ‟a‟, ‟n‟,‟ k‟})
MATHEMATICAL OPERATIONS : INTERSECTION
 s1.intersection(s2) :
 The intersection() method returns the intersection of a
set and the set of elements in an iterable object s2.
Sometimes, the & operator is used in place of
the intersection() method, but it only operates on
the set of elements in set.
Syntax: s1.intersection(s2)# here s2 can be set, list,
tuple, dictionary
or
s1&s2 # here s2 must be set only.
Example:
s1={0,1,2,6}
s2={34,54,6}
print(s1.intersection(s2)) #{6}
MORE EXAMPLES ON INTERSECTION
 s=set(“Hacker”)
 print(s.intersection(“Rank”))
 print(s.intersection([„R‟,‟a‟,‟n‟,‟k‟]))
 Print(s.intersection((„R‟,‟a‟,‟n‟,‟k‟)))
 Print(s.intersection({“Rank”:1}))
 Note: when we use dictionary as an argument to
union it will add key only in a union set.
 print(s&“Rank”)
 print(s&[„R‟, ‟a‟, ‟n‟, ‟k‟] )
 Print(s&(„R‟, ‟a‟, ‟n‟, ‟k‟))
 Print(s&{“Rank”:1})
 Print(s&{„R‟, ‟a‟, ‟n‟,‟ k‟})
MATHEMATICAL OPERATIONS: INTERSECTION_UPDATE
s1.intersection_update(s2) :
This method update s1 with the intersection of
s1 and s2 (iterable object) given in argument by
removing the items in s1 that are not present in
both s1 and s2.
This method returns None
Syntax: s1.intersection_update(s2)
Example:
>>S1={2,4,5,0}
>>S2={5,0,9,8}
>>print(s1.intersection_update(s2)) #None
>>s1. intersection_update(s2) #
>>s1 # {5,0}
MATHEMATICAL OPERATIONS: DIFFERENCE
s1.difference(s2) :
The difference() returns a set with all the elements
from the set that are in s1 but not in an iterable
s2.
Sometimes the - operator is used in place of
the difference() , but it only operates on the set of
elements in set.
Syntax: s1.difference(s2) #here s2 can be set, list,
tuple, dictionary
or
s1-s2 # here s2 must be set only.
Example:
>>S1={2,4,5,0}
>>S2={5,0,9,8}
>>print(s1.difference(s2)) # {2,4}
MATHEMATICAL OPERATIONS: DIFFERENCE_UPDATE
s1.difference_update(s2) :
This method update s1 with the difference of s1
and s2 ( iterable object) given in argument by
removing the items that exist in both sets.
This method returns None
Syntax: s1.difference_update(s2)
Example:
>>S1={2,4,5,0}
>>S2={5,0,9,8}
>>print(s1.intersection_update(s2)) #None
>>s1. difference_update(s2) #
>>s1 # {2,4}
MATHEMATICAL OPERATIONS: SYMMETRIC_DIFFERENCE
s1.symmetric_difference(s2) :
Return a set that contains all items from both
sets, except items that are present in both sets:
Sometimes the ^ operator is used in place of
the symmetric_difference() , but it only operates on
the set of elements in set.
Syntax: s1.symmetric_difference(s2) #here s2 can
be set, list, tuple, dictionary
or
s1^s2 # here s2 must be set only.
Example:
>>S1={2,4,5,0}
>>S2={5,0,9,8}
>>print(s1.symmetrci_difference(s2)) # {2,4,9,8}
MATHEMATICAL OPERATIONS : SYMMETRIC_DIFFERENCE_UPDATE
s1.symmetric_difference_update(s2) :
This method update s1 with the
symmetric_difference()of s1 and s2 ( iterable
object)
This method returns None
Syntax: s1.symmetric_difference_update(s2)
Example:
>>S1={2,4,5,0}
>>S2={5,0,9,8}
>>print(s1.intersection_update(s2)) #None
>>s1. symmetric_difference_update(s2) #
>>s1 # {2,4,9,8}
MATHEMATICAL OPERATIONS: ISDISJOIN()
s1.isdisjoint(s2) :
Return True if no items in set s1 is present in
set s2.
Syntax: s1.isdisjoint(s2) #here s2 can be set, list,
tuple, dictionary
Example:
>>s1={2,4,5,0}
>>s2={5,0,9,8}
>>print(s1.isdisjoint(s2)) # False
>>s2={3,7}
>> print(s1.isdisjoint(s2)) # True
MATHEMATICAL OPERATIONS: ISSUBSET()
s1.issubset(s2) :
Return True if all items in set s1 are present in set s2.
Sometimes the <= operator is used in place of
the issubset() , but it only operates on the set of
elements in set.
Syntax: s1.issubset(s2) #here s2 can be set, list,
tuple, dictionary
Or
s1 < = s2
Example:
>>s1={2,4,5,0}
>>s2={5,0,9,8}
>>print(s1.issubset(s2)) # False
>>s2={2,4,5,0,9,8}
>> print(s1.issubset(s2)) # True
MATHEMATICAL OPERATIONS: ISSUPERSET()
s1.issuperset(s2) :
Return True if all items in set s2 are present in set s1.
Sometimes the >= operator is used in place of
the issuperset() , but it only operates on the set of
elements in set.
Syntax: s1.issuperset(s2) #here s2 can be set, list,
tuple, dictionary
Or
s1 > = s2
Example:
>>s1={2,4,5,0}
>>s2={5,0,9,8}
>>print(s1.issuperset(s2)) # False
>>s2={2,4,5}
>> print(s1.issuperset(s2)) # True
SET COMPREHENSION
 Like list comprehensions, set comprehensions offer
an easy way of creating sets. It consists of braces
containing an expression followed by a for clause,
and zero or more for or if clauses.
 General form of set comprehension is:
s={ expression for var in sequence [optional for
and/or if] }
Example:
a={ x**2 for x in range(5) }
print(a) #
b={ num for num in a if num > 2 and num < 10 }
print(b)
DICTIONARY IN PYTHON : INTRODUCTION
 Python dictionary is mutable and an unordered collection of
items where each item of a dictionary has a key/value pair.
 Each key is separated from its value by a colon (:).
 The items are separated by commas, and the whole thing is
enclosed in curly braces.
 An empty dictionary without any items is written with just
two curly braces, like this: {}.
 Keys are unique within a dictionary while values may not
be.
 The values of a dictionary can be of any type, but the keys
must be of an immutable data type such as strings,
numbers, or tuples.
 The values can be of any data type and can repeat, but keys
must be of immutable type (string, number or tuple with
immutable elements) and must be unique.
DICTIONARY IN PYTHON : INTRODUCTION (CONT..)
 Dictionary keys are case sensitive, same name
but different cases of Key will be treated distinctly.
 Syntax: d={key1:value1, key2:value2,….}
 Example:
d={} #empty dictionary
d1={1:‟one‟,4:‟four‟,9:‟nine‟}
print(d1)
dict = {'Name': „Xyz', 'Age': 18, 'Class': „Third'};
print("dict['Name']: ", dict['Name'])
Dict = {'Name': „XYZ', 1: [1, 2, 3, 4]}
print("nDictionary with the use of Mixed Keys: ")
print(Dict)
DICTIONARY : ACCESSING ELEMENTS
 While indexing is used with other data types to access
values, a dictionary uses keys.
 Keys can be used either inside square brackets [] or with
the get() method.
 If we use the square brackets [], KeyError is raised in case a
key is not found in the dictionary.
 On the other hand, the get() method returns None if the key
is not found.
 Example:
 # get Vs [] for retrieving elements
d={'name': „XYZ', 'age': 26}
print(d['name']) # XYZ
print(d.get('age')) # 26
print(d.get('address'))#None
print(d['address'])#KeyError
DICTIONARY : ITERATING USING FOR LOOP
 Dictionary can be iterated over in following ways:
d={'name' : 'XYZ', 'age' : 25, 'salary' : 3445}
for k in d:
print(k) # prints all keys of the dictionary
 Iterate over key-value pairs:
for x in d.items():
print(x) # prints tuples of key-value pair
for k, v in d.items():
print(k, v) # prints key-value pairs
 Iterate over keys:
for k in d.keys():
print(k) # prints keys
 Iterate over values:
for v in d.values():
print(v) # prints values
DICTIONARY : OPERATIONS
 We can change the value of a specific item by
referring to it‟s key name.
 Example:
d={'name' : 'XYZ', 'age' : 25, 'salary' : 3445}
d['salary']=10000
print(d)
 We can also check if key exists using membership
operator.
 Example:
d={'name' : 'XYZ', 'age' : 25, 'salary' : 3445}
if 'age' in d:
print(„Yes, age is one of the key in
dictionary')
DICTIONARY : DELETING KEY FROM DICTIONARY
 By using del keyword we can remove the item
with the specified key name.
 Example:
d={'name' : 'XYZ', 'age' : 25, 'salary' : 3445}
del d['salary„]
print(d)
 We can also delete the complete dictionary
using del keyword.
 Example:
d={'name' : 'XYZ', 'age' : 25, 'salary' : 3445}
del d
print(d) # NameError: name 'd' is not defined
DICTIONARY : BUILT-IN METHODS
 Consider, d={1:'one', 4:‘four', 9:‘nine'}
 sum() : calculate and return sum of all keys of d if
keys are numeric.
 Example: print(sum(d)) #14
 min() : returns minimum of all keys in d.
 Example: print(min(d)) # 1
 max() : returns maximum of all keys in d.
 Example: print(max(d)) # 9
 len() : returns number of key - value pairs.
 Example : print(len(d)) # 3
 sorted() : returns list by sorting the dictionary in
ascending order based on keys.
 Example : print(sorted(d)) # [1,4,9]
DICTIONARY : METHODS
 Consider, d={8:‘eight', 4:‘four', 9:‘nine'}
 Clear(): Removes all the elements from the dictionary. It returns
None
 Syntax: d.clear()
 Example:
d.clear() # d is dictionary
print(d) #{}
 Copy(): Returns a copy of the dictionary.
 Syntax: d.copy()
 Example:
 d1=d.copy()
 d[8]=„example‟
 print(d)#
 print(d1)#
DICTIONARY : METHODS
 Consider, d={8:‘eight', 4:‘four', 9:‘nine'}
 fromkeys(): Returns a dictionary with the specified keys and a value.
 Syntax: dict.fromkeys(seq [, value])
 Note:Value is optional, if not provided None will be added as
value.
 Example:
d={}
x={„a‟, „v‟, „k‟}
d1=d.fromkeys(x) #
print(d1) # d1={„a‟:None, „v‟: None,‟k‟:None}
y=10
d2=d.fromkeys(x, y)
print(d2) # d1={„a‟:10, „v‟: 10, ‟k‟ :10}
z=[1,2]
d3= d.fromkeys(x, z)
print(d3) # d1={„a‟:[1, 2], „v‟: [1, 2], ‟k‟ :[1, 2]}
DICTIONARY : METHODS
 Consider, d={8:‘eight', 4:‘four', 9:‘nine'}
 get(): The get() method returns the value of the item
with the specified key.
 Syntax: d.get(key [,value])
 Note:Value is optional, A value to return if the
specified key does not exist. Default value None.
 Example:
x=d.get(8,‟xyz‟)
print(x)
y=d.get(7,‟abc‟)
print(y)
DICTIONARY : METHODS
 Consider, d={8:‘eight', 4:‘four', 9:‘nine'}
 items(): The items() method returns a view
object. The view object contains the key-value
pairs of the dictionary, as tuples in a list.
 The view object will reflect any changes done to
the dictionary, see example below.
 Syntax: d.items() #where d is dictionary.
 Example:
x=d.items()
print(x)
d[8]=„xyz‟
print(d)
print(x)
DICTIONARY : METHODS
 Consider, d={8:‘eight', 4:‘four', 9:‘nine'}
 keys(): The keys() method returns a view object.
The view object contains the keys of the
dictionary, as a list.
 The view object will reflect any changes done to
the dictionary, see example below.
 Syntax: d.keys() #where d is dictionary.
 Example:
x=d.keys()
print(x)
d[1]=„one‟
print(d)
print(x)
DICTIONARY : METHODS
 Consider, d={8:‘eight', 4:‘four', 9:‘nine'}
 pop(): The pop() method removes the specified item
from the dictionary.
 The value of the removed item is the return value
of the pop() method.
 Syntax: d.pop(key [,defaultValue]) #where d is
dictionary.
 Note: Optional. A value to return if the specified
key do not exist.
 Example:
print(d.pop(8,‟hello‟))#eight
print(d.pop(1,‟hello‟)) #hello
print(d.pop(2))# KeyError
DICTIONARY : METHODS
 Consider, d={8:‘eight', 4:‘four', 9:‘nine'}
 popitem(): method removes the item that was last
inserted into the dictionary.
 The removed item is the return value of
the popitem() method, as a tuple
 Syntax: d.popitem() #where d is dictionary.
 Example:
print(d.popitem())#
DICTIONARY : METHODS
 Consider, d={8:‘eight', 4:‘four', 9:‘nine'}
 setdefault(): The setdefault() method returns the value of the
item with the specified key.
 If the key does not exist, insert the key, with the specified
value.
 Syntax: d.setdefault(key [,value]) #where d is dictionary.
 Note: Value is Optional.
If the key exist, this parameter has no effect.
If the key does not exist, this value becomes the key's value.
Default value None
 Example:
print(d.setdefault(8,‟hello‟))#eight
print(d.setdefault(1,‟hello‟)#inserts 1:hello & return hello
Print(d.setdefault(2)#None
DICTIONARY : METHODS
 Consider, d={8:‘eight', 4:‘four', 9:‘nine'}
 update(): The update() method inserts the specified items to
the dictionary. It returns None.
 The specified items can be a dictionary, or an iterable object
with key value pairs.
 Syntax: d.update(iterable) #where d is dictionary.
 Example:
d.update([(2,‟two‟),(3,‟three‟)])
print(d)#
d.update(((4,‟two‟),(5,‟three‟)))
print(d)
d.update({0:‟zero‟,6:‟six‟})
print(d)
DICTIONARY : METHODS
 Consider, d={8:‘eight', 4:‘four', 9:‘nine'}
 values(): The values() method returns a view object. The view
object contains the values of the dictionary, as a list.
 The view object will reflect any changes done to the dictionary.
 Syntax: d.values() #where d is dictionary.
 Example:
X=d.values()
print(X)
d[8]=„example‟ # Changes will be reflected in X also.
print(d)
print(X) #
DICTIONARY : METHODS
 Consider, d={8:‘eight', 4:‘four', 9:‘nine'}
 __len__(): The __len__() method returns length of
dictionary.
 Syntax: d.__len__() #where d is dictionary.
 Example:
X=d.__len__()
print(X)
NESTED DICTIONARY:
 Dictionary within dictionary is called nested
dictionary is called nested dictionary.
 Example:
Employee={
'xyz': {'dob':'23/12/2020','age':23},
'abc': {'dob':'13/04/2021','age':20},
'pqr': {'dob':'21/02/2019','age':18}
}
print(Employee)
ITERATING OVER NESTED DICTIONARY:
for i,j in Employee.items():
print(i,j)
for i in Employee.items():
print(i)
for i in Employee.keys():
print(i)
for i in Employee.values():
print(i)
Dictionary Comprehension
General form is:
d={key:value for (key,value) in d.items()}
 Example:
d={„a‟:1,‟b‟:2,‟c‟:3,‟d‟:4,‟e‟:5}
#Obtain dictionary with each value cubed
d1={k:v**3 for (k,v) in d.items()}
print(d1)#dictionary with each value cubed
#obtain dictionary with each value cubed if value>3
d2={k:v for (k,v) in d.items() if v>3}
print(d2)
#Identify odd and even entries in the dictionary
d3={k:(„EVEN‟ if v%2==0 else „ODD‟) for (k,v) in
d.items()}
Dictionary Comprehension
 Create two lists students and marks. Create a
dictionary from these two lists using dictionary
comprehension. Use names as keys and marks as
values.
 Answer:
lstnames=[„Sunil‟,‟Anuj‟,‟Rahul‟,‟Anuja‟,‟Rohit‟]
lstmarks=[54,65,45,67,78]
d={k:v for (k,v) in zip(lstnames,lstmarks)}
print(d)
Problem Statement: 01
 Write a program that reads a string from
the keyboard and creates dictionary
containing frequency of each character
occuring in the string.
Problem Statement: 02
 A sparse matrix is a matrix most of
whose elements have a value 0. Suppose
we have a 5x5 sparse matrix stored as a
list of lists. Dictionary should store the
row and column of a non-zero element
as a tuple key and the value of the non-
zero element as the value against the
key tuple.
Problem Statement: 03
 Given the following dictionary:
 Marks={„subu‟:{„Math‟:88,‟Eng‟:60,‟Sst‟:95},
„Amol‟:{„Math‟:78,‟Eng‟:68,‟Sst‟:89},
„Rama‟:{„Math‟:68,‟Eng‟:66,‟Sst‟:87},
„Raka‟:{„Math‟:88,‟Eng‟:68,‟Sst‟:95}}
Write a program to perform the following
operations:
a) Print marks obtained by amol in English
b) Set marks obtained by Rama in Maths to
77
c) Sort the dictionary by name
Problem Statement: 04
 Create a dictionary which stores following data:
Interface IP Address status
Eth0 1.1.1.1 up
Eth1 2.2.2.2 up
Wlan0 3.3.3.3 down
Wlan1 4.4.4.4 up
 Write a program to perform following
operations:
a) Find the status of a given interface
b) Find Interface and IP of all interfaces which
are up.
c) Find the total number of interfaces
d) Add two new entries to the dictionary.

More Related Content

Similar to Data Structures in Python

The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196Mahmoud Samir Fayed
 
Session -5for students.pdf
Session -5for students.pdfSession -5for students.pdf
Session -5for students.pdfpriyanshusoni53
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methodsnarmadhakin
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptxRamiHarrathi1
 
The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212Mahmoud Samir Fayed
 
15CS664- Python Application Programming - Module 3
15CS664- Python Application Programming - Module 315CS664- Python Application Programming - Module 3
15CS664- Python Application Programming - Module 3Syed Mustafa
 
15CS664-Python Application Programming - Module 3 and 4
15CS664-Python Application Programming - Module 3 and 415CS664-Python Application Programming - Module 3 and 4
15CS664-Python Application Programming - Module 3 and 4Syed Mustafa
 
The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 22 of 185
The Ring programming language version 1.5.4 book - Part 22 of 185The Ring programming language version 1.5.4 book - Part 22 of 185
The Ring programming language version 1.5.4 book - Part 22 of 185Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 21 of 180
The Ring programming language version 1.5.1 book - Part 21 of 180The Ring programming language version 1.5.1 book - Part 21 of 180
The Ring programming language version 1.5.1 book - Part 21 of 180Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 22 of 181
The Ring programming language version 1.5.2 book - Part 22 of 181The Ring programming language version 1.5.2 book - Part 22 of 181
The Ring programming language version 1.5.2 book - Part 22 of 181Mahmoud Samir Fayed
 
The Ring programming language version 1.2 book - Part 12 of 84
The Ring programming language version 1.2 book - Part 12 of 84The Ring programming language version 1.2 book - Part 12 of 84
The Ring programming language version 1.2 book - Part 12 of 84Mahmoud Samir Fayed
 

Similar to Data Structures in Python (20)

Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196
 
Session -5for students.pdf
Session -5for students.pdfSession -5for students.pdf
Session -5for students.pdf
 
6. list
6. list6. list
6. list
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx
 
Python lists
Python listsPython lists
Python lists
 
The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212
 
15CS664- Python Application Programming - Module 3
15CS664- Python Application Programming - Module 315CS664- Python Application Programming - Module 3
15CS664- Python Application Programming - Module 3
 
15CS664-Python Application Programming - Module 3 and 4
15CS664-Python Application Programming - Module 3 and 415CS664-Python Application Programming - Module 3 and 4
15CS664-Python Application Programming - Module 3 and 4
 
The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189
 
The Ring programming language version 1.5.4 book - Part 22 of 185
The Ring programming language version 1.5.4 book - Part 22 of 185The Ring programming language version 1.5.4 book - Part 22 of 185
The Ring programming language version 1.5.4 book - Part 22 of 185
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Pytho_tuples
Pytho_tuplesPytho_tuples
Pytho_tuples
 
The Ring programming language version 1.5.1 book - Part 21 of 180
The Ring programming language version 1.5.1 book - Part 21 of 180The Ring programming language version 1.5.1 book - Part 21 of 180
The Ring programming language version 1.5.1 book - Part 21 of 180
 
Python lists &amp; sets
Python lists &amp; setsPython lists &amp; sets
Python lists &amp; sets
 
The Ring programming language version 1.5.2 book - Part 22 of 181
The Ring programming language version 1.5.2 book - Part 22 of 181The Ring programming language version 1.5.2 book - Part 22 of 181
The Ring programming language version 1.5.2 book - Part 22 of 181
 
Unit - 4.ppt
Unit - 4.pptUnit - 4.ppt
Unit - 4.ppt
 
The Ring programming language version 1.2 book - Part 12 of 84
The Ring programming language version 1.2 book - Part 12 of 84The Ring programming language version 1.2 book - Part 12 of 84
The Ring programming language version 1.2 book - Part 12 of 84
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
 

Recently uploaded

How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 

Recently uploaded (20)

How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 

Data Structures in Python

  • 1. UNIT-03: DATA STRUCTURES IN PYTHON [14 MARKS] BY MS. A. V. WANKAR
  • 2. 4 DATA STRUCTURES IN PYTHON 1. List 2. Tuple 3. Set 4. Dictionary
  • 3. LISTS lists can be heterogeneous • a = [„hello', „example', 100, 1234, 2*2] Lists can be indexed and sliced: • a[0]  „hello‟ • a[:2]  [„hello', 'example'] Lists can be manipulated • a[2] = a[2] + 23 • a[0:2] = [1,12] • a[0:0] = [] • len(a)  5
  • 4. LIST VARIETIES  It is possible to create a new list from another.  Example:  A=[1,34.5,’hello’,2+3j]  B=A # copies all elements of A to B, both points to same list, Changing one changes the other.  It is possible to create a list of lists:  Example:  List 1= [2, 5, 3]  List2=[1,34,6]  List3=[List1,List2]  Print(List3)#[[2,5,3],[1,34,6]]
  • 5. LIST VARIETIES (CONT…)  A list can be embedded in another list.  Example:  A=[1,2,3,4]  B=[10,20,A,30]  Print(B) # [10,20,[1,2,3,4],30]  It is possible to unpack a list within a list using the * operator.  Example:  A= [1, 2, 3,4]  B=[10,20,*A,30]  Print(B) # [10,20,1,2,3,4,30]
  • 6. LIST METHODS  append(x): append element x at the end of list & does not return anything. i.e. None is returned  Syntax: list. append (x)  Example: • # Adds List Element as value of List. • List = ['Mathematics', 'chemistry', 1997, 2000] • List.append(20544) • print(List)#5
  • 7. LIST METHODS  extend(List2): append all items in List2 to list l, returns None.  Syntax: List1.extend(List2)  Example: •List1 = [1, 2, 3] •List2 = [2, 3, 4, 5] •# Add List2 to List1 •List1.extend(List2) •print(List1) •# Add List1 to List2 now •List2.extend(List1) •print(List2)
  • 8. LIST METHODS  insert(i, x): Insert element x at index i (i should be within range , otherwise we get Index Error ), returns None.  Syntax: list.insert(index, x)  Example: •List = ['Mathematics', 'chemistry', 1997, 2000] •# Insert at index 2 value 10087 •List.insert(2,10087) •print(List)
  • 9. LIST METHODS  count(x): Returns total occurrence of element x in List  Syntax: List.count(x)  Example: •List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] •print(List.count(1))  index(x) : Returns the index of first occurrence of x  Syntax: List.index(x[,start][,end])  Example: •List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] •print(List.index(2)) •Print(List.index(2,2)) •Print(List.index(2,5,9) # it will search in start=5 and end=9-1
  • 10. LIST METHODS  pop([index]) : Index is not a necessary parameter, if not mentioned pops and returns element at the last index.  Syntax: list.pop([index])  Example:  List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]  print(List.pop())  print(List.pop(0))  remove(x): remove first occurance of element x from list, returns None.  Syntax: list. remove(x)  Example:  List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]  List.remove(3)  print(List)
  • 11. LIST METHODS  reverse(): It simply reverses the list, returns None.  Syntax: List.reverse()  Example:  List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]  List.reverse()  print(List)  sort() : Sorts the list in Place  Syntax: List.sort([key,[Reverse_flag]])  Example:  List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]  Print(List.sort())  #Reverse flag is set True  List.sort(reverse=True)  print(List)
  • 12. LIST METHODS  clear(): It simply reverses the list, returns None.  Syntax: List.clear()  Example:  List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]  List.clear()  print(List)# prints empty list  copy() : copy elements of List. Returns List  Syntax: List.copy()  Example:  List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]  L=List.copy()  print(L)
  • 13. DELETING ELEMENT USING DEL del list[index]: Element to be deleted is mentioned using list name and index. remove by index, not value remove slices from list (rather than by assigning an empty list)  Syntax: del list[index] or del list[start_index : end_index]  Example:  List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]  del List[0]  del List[3:5] # removes elements from index start to end-1  Print(List)
  • 14. BUILT-IN FUNCTIONS OF LIST  sum() : Calculates & Returns sum of all the elements of List.  Syntax: sum(List)  Example:  List = [1, 2, 3, 4, 5]  print(sum(List))  Note: Sum is calculated only for Numeric values, elsewise throws TypeError.  len() :Calculates & Returns total length of List.  Syntax: len(list_name)  Example:  List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]  print(len(List))
  • 15. BUILT-IN FUNCTIONS OF LIST  min() : Calculates & Returns minimum of all the elements of List.  Syntax: min(List)  Example:  List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]  print(min(List))  max() :Calculates & Returns maximum of all the elements of List.  Syntax: max(List)  Example:  List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]  print(max(List))
  • 16. BUILT-IN FUNCTIONS OF LIST  sorted() : returns a sorted list of the specified list.  Syntax: sorted(list[,key[, Reverse_Flag ] ])  Example:  List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]  l1=sorted(List)  Print(l1)  l2=sorted(List, reverse=True)  Print(l2) Note: if Reverse_Flag = True then sorts in descending order otherwise sort in ascending order, by default Reverse_Flag = False.
  • 17. USING ALL() BUILT-IN FUNCTIONS  This function returns true if all of the items are True (or if the iterable is empty).  All can be thought of as a sequence of AND operations on the provided iterables.  Syntax: all(list of iterables)  Example:  # print (all([True, True, True, True])) # Here all the iterables are True so all will return True and the same will be printed  print (all([False, True, True, False])) # False  print (all([False, False, False])) # False
  • 18. USING ANY() BUILT-IN FUNCTIONS  Returns true if any of the items is True.  It returns False if empty or all are false. Any can be thought of as a sequence of OR operations on the provided iterables.  Syntax: any(list of iterables)  Example:  # print (any([False, False, False, False])) # Here all the iterables are False so any will return False and the same will be printed  print (any([False, True, False, False])) # True  print (any([True, False, False, False])) # True
  • 19. LIST COMPREHENSION  A list comprehension offers an easy way of creating lists.  It consists of brackets containing expression followed by a for clause, and zero or more for or if clause.  Used when you want to create a new list based on the values of an existing list.  Syntax:  Newlist = [expression for item in iterable/sequence [optional for and/or if] ]
  • 20. LIST COMPREHENSION (CONT.…)  Example: A = [0,5,6,3,2,9,8,4] B=[] for i in A:  if i>=5:  B.append(i) print(B) # [5,6,9,8]  Same can be done in One line using list comprehension L=[x for x in A if x>=5] print(L) # [5,6,9,8]
  • 21. LIST COMPREHENSION (CONT.…) >>> a = [2,4,6] >>> [3*x for x in a] [6, 12, 18] >>> [{x: x**2} for x in a} [{2: 4}, {4: 16}, {6: 36}] >>> [[x, x**2] for x in a] [[2, 4], [4, 16], [6, 36]] >>> [[x, x**2] for x in a] [[2, 4], [4, 16], [6, 36]]
  • 22. LIST COMPREHENSION (CONT.…) cross products: >>> vec1 = [2,4,6] >>> vec2 = [4,3,-9] >>> [x*y for x in vec1 for y in vec2] [8,6,-18, 16,12,-36, 24,18,-54] >>> [ x+y for x in vec1 for y in vec2] [6,5,-7,8,7,-5,10,9,-3] >>> [vec1[i]*vec2[i] for i in range(len(vec1))] [8,12,-54]
  • 23. LIST COMPREHENSIONS can also use if: >>> [3*x for x in vec if x > 3] [12, 18] >>> [3*x for x in vec if x < 2] []
  • 24. LIST COMPREHENSION (CONT.…) >>> a = [(i, j) for i in [1,2] for j in [1,2] if i!=j] >>>print(a) [ (1,2),(2,1) ] >>> a=[(i, j, k) for i in [1,2,3] for j in [1, 2, 3] for k in [1, 2, 3] if i!=j and j!=k and k!=i] >>> print(a) [(1,2,3), (1,3,2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] >>> arr=[[1,2,3,4], [5,6,7,8]] >>>b=[n for ele in arr for n in ele] >>>print(b) [1,2,3,4,5,6,7,8]
  • 25. TUPLES: INTRODUCTION  A simple immutable ordered sequence of items.  Items can be of mixed types, including collection types.  tuples are defined using parentheses and commas.  Example: t = (23,„abc‟,4.56,(2,3),„xyz‟)  individual members of a tuple are accessed by using positive and negative index starting with „0‟ similar to the lists.  Example: print(t[0]) # prints 23 print(t[-1]) # prints „xyz‟
  • 26. TUPLES: DEFINING TUPLES  Using parenthesis to define tuple is optional.  Example: a=10;b=20;c=30 t=a, b, c or t=(a, b, c) print(t)  Empty tuple can be created as shown below.  Example: t=() print(t)#()  A tuple with single value can be created as..  Example: t=(23,)  Note: note the comma (,) written after 23. If we don‟t give this comma then t will be created as a normal variable instead of tuple.
  • 27. TUPLES: UNPACKING  It is possible to unpack tuples & also lists.  Example: a=t[0] b=t[1] c=t[2] (a, b, c)=t or a, b, c=t  If the number of variables are less than the number of values then we can add an * to the variable name and the values will be assigned to the variable as a list:  Example1: t = (23,„abc‟,4.56,(2,3),„xyz‟) (a, b, *c)=t print(c)
  • 28. TUPLES: UNPACK CONT..  Example2: t = (23,„abc‟,4.56,(2,3),„xyz‟) (a, *b, c)=t print(a)#23 Print(b)#[„abc‟,4.56,(2,3)] print(c)#xyz  It is possible to unpack tuple within another tuple.  Example: t1=(100,*t) print(t1) # (100,23,‟abc‟,4.56,(2,3),‟xyz‟)
  • 29. TUPLES: SLICE/CUT OPERATOR ([:])  We can use cut/slice operator ([:]) with tuples similar to the lists.  Example: t=(23,45,56.4,3+6j,‟abc‟) print(t[2:])#(56.4,3+6j,‟abc‟)  We can print all elements of tuple using cut/slice operator ([:]) similar to lists.  Example: t=(23,45,56.4,3+6j,‟abc‟) print(t[:])#(23,45,56.4,3+6j,‟abc‟)  Similar to the lists we can print tuple in a reverse using cut/slice operator ([:])  Example: t=(23,45,56.4,3+6j,‟abc‟) print(t[::-1])#(23,45,56.4,3+6j,‟abc‟)
  • 30. TUPLE VARIETIES  It is possible to create a new tuple from another.  Example:  A=(1,34.5,’hello’,2+3j)  B=A # copies all elements of A to B, both points to same tuple.  It is possible to create a tuple of tuple:  Example:  t1= (2, 5, 3)  t2=(1,34,6)  t3=(t1, t2)  print(t3)#((2,5,3),(1,34,6))
  • 31. LIST VARIETIES (CONT…)  A tuple can be embedded in another tuple.  Example:  A=(1,2,3,4)  B=(10,20,A,30)  print(B) # (10,20,(1,2,3,4),30)  Similar to lists, it is possible to concatenate two tuples.  Example:  A= (1, 2, 3,4)  B=(10,20,30)  C=A+B  print(C) # (1,2,3,4,10,20,30)
  • 32. TUPLES: METHODS  1. t.count() : the count() method returns the number of times a specified value appears in the tuple.  Syntax: t.count(value)# value is nothing but item to search for in tuple t.  Example: t=(23,45,23,56.4,3+6j,‟abc‟) print(t.count(23))#2  2. t.index() : Search for the first occurrence of the value 8, and return its position.  Syntax: t.index(value)# value is nothing but item to search for in tuple t.  Example: t=(23,45,23,56.4,3+6j,‟abc‟) print(t.index(23))#0
  • 33. TUPLES: BUILT-IN FUNCTIONS  1. t.count() : the count() method returns the number of times a specified value appears in the tuple.  Syntax: t.count(value)# value is nothing but item to search for in tuple t.  Example: t=(23,45,23,56.4,3+6j,‟abc‟) print(t.count(23))#2  2. t.index() : Search for the first occurrence of the value 8, and return its position.  Syntax: t.index(value)# value is nothing but item to search for in tuple t.  Example: t=(23,45,23,56.4,3+6j,‟abc‟) print(t.index(23))#0
  • 34. BUILT-IN FUNCTIONS OF TUPLE  sum() : Calculates & Returns sum of all the elements of tuple.  Syntax: sum(t)  Example:  t = (1, 2, 3, 4, 5)  print(sum(t))  Note: Sum is calculated only for Numeric values, elsewise throws TypeError.  len() :Calculates & Returns total length of tuple.  Syntax: len(tuple_name)  Example:  t = (1, 2, 3, 1, 2, 1, 2, 3, 2, 1)  print(len(t))
  • 35. BUILT-IN FUNCTIONS OF TUPLE  min() : Calculates & Returns minimum of all the elements of tuple.  Syntax: min(t)  Example:  t = (2.3, 4.445, 3, 5.33, 1.054, 2.5)  print(min(t))  max() :Calculates & Returns maximum of all the elements of tuple.  Syntax: max(t)  Example:  t = (1, 2, 3, 1, 2, 1, 2, 3, 2, 1)  print(max(t))
  • 36. BUILT-IN FUNCTIONS OF TUPLE  sorted() : returns a sorted list of the specified tuple.  Syntax: sorted(tuple_name[,key[, Reverse_Flag ] ])  Example:  t= [2.3, 4.445, 3, 5.33, 1.054, 2.5]  l1=sorted(t)  Print(l1)  l2=sorted(List, reverse=True)  Print(l2) Note: if Reverse_Flag = True then sorts in descending order otherwise sort in ascending order, by default Reverse_Flag = False.
  • 37. USING ALL() BUILT-IN FUNCTIONS  This function returns true if all of the items are True (or if the iterable is empty).  All can be thought of as a sequence of AND operations on the provided iterables.  Syntax: all(list of iterables)  Example:  # print (all((True, True, True, True))) # Here all the iterables are True so all will return True and the same will be printed  print (all((False, True, True, False))) # False  print (all((False, False, False))) # False
  • 38. USING ANY() BUILT-IN FUNCTIONS  Returns true if any of the items is True.  It returns False if empty or all are false. Any can be thought of as a sequence of OR operations on the provided iterables.  Syntax: any(list of iterables)  Example:  # print (any((False, False, False, False))) # Here all the iterables are False so any will return False and the same will be printed  print (any((False, True, False, False))) # True  print (any((True, False, False, False))) # True
  • 39. USING ZIP() BUILT-IN FUNCTIONS  The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together and so on …..  Syntax: zip(*iterables) # can be anything like lists, tuples etc.  If we do not pass any parameter, zip() returns an empty iterator.  If a single iterable is passed, zip() returns an iterator of tuples with each tuple having only one element.  If the passed iterators have different lengths, the iterator with the least items decides the length of the new iterator.
  • 40. USING ZIP() BUILT-IN FUNCTIONS  Example1: a=zip() b=list(a) print(b)#[]  Example2: number_list = [1, 2, 3] str_list = ['one', 'two', 'three'] Result=zip(number_list,str_list) R=list(Result) print(R)
  • 41. UNZIPPING THE ZIPPED LIST  The * operator can be used in conjunction with zip() to unzip the list. a=zip() Example: number_list = [1, 2, 3] str_list = ['one', 'two', 'three'] Result=zip(number_list,str_list) R=tuple(Result) num, str=zip(*R) print(num) print(str)
  • 42. PROBLEM STATEMENT: 01  Create 3 lists – a list of names, a list of ages, a list of salaries. Generate and print a list of tuples containing name, age and salary from the 3 lists. From this list generate 3 tuples – one containing all names, another containing all ages and third containing all salaries.
  • 44. PROBLEM STATEMENT: 02  Create a list of tuples. Each tuple should contain an item and its price in float. Write a program to sort the tuples in descending order by price.
  • 45. USING DIVMOD() BUILT-IN FUNCTION  divmod() function takes two argument and return the tuple of quotient and the reminder.  Example1: Result=divmod(17,3) print(Result)  Example2: t=(17,3) R=divmod(*t) print(R)
  • 46. PRACTICE QUESTIONS: a) Write a program to obtain transpose of a 3x4 matrix using zip(). b) Write a program to multiply two matrices x(2x3) and y(2x2) using list comprehension and zip function. c) Suppose we have a list of 5 integers and a tuple of 5 floats. Can we zip them and obtain an iterator. If yes, how ? d) Write a program to unzip a list of tuples into individual lists e) Suppose a date is represented as a tuple (d, m, y). Write a program to create 2 date tuples and find the number of days between the two dates.
  • 47. ASSIGNMENT NO: 03 Store the data about shares held by a user as tuples containing the following information about shares. Share name Date of purchase Cost price Number of shares Selling price Write a program to determine: a) Total cost of portfolio b) Total amount gained or lost. c) Percentage profit made or loss incurred.
  • 48. SET IN PYTHON: INTRODUCTION  A set is an unordered collection of items which are separated by comma (,) and enclosed in curly brackets ({ }).  Items of a set can be of any data type.  set do not contain duplicate values  Example: A={20} # set with 1 value. B={„abc‟,34,7+3j,90.45} # set with multiple items. C={10,10,10,10} # only 1 10 gets stored.
  • 49. SET IN PYTHON: INTRODUCTION (CONT…)  Set is an unordered collection, hence order of insertion is not same as the order of access.  Example: A={15,25,35,45,55} print(A) # doesn‟t always print {15,25,35,45,55}  The elements in the set are immutable(cannot be modified) but the set as a whole is mutable i.e. We can add or remove items from it.
  • 50. SET IN PYTHON: INTRODUCTION (CONT…)  A set() function can be used to convert a string, , list or tuple into a set.  Example: L=[10,20,30,40,50] T=(„abc‟, 25, 32.435) S=„Programming‟ S1=set(L) #{30, 20, 10, 40, 50} S2=set(T) # {„abc‟, 32.435, 25} S3=set(S) #{„P‟, ‟r‟, „g‟, „o‟, „m‟, „n‟,‟g‟ }  Note: While creating set using set(), repetitions are eliminated.
  • 51. CREATING EMPTY SET  Empty set can be created by using a set() constructor.  Example: S={} # It will create empty dictionary S=set() # It will create empty set  Note: It is not possible to create empty set by using {} , instead it creates empty dictionary. To create empty set, we must use set() constructor.
  • 52. ACCESSING SET ELEMENTS:  Being an unordered collection, items in a set cannot be accessed using indices.  Sets can not be sliced using [].  Entire set can be printed by just using the name of the set.  Example: S={10, 20, 30, 40, 50} #{30, 20, 10, 40, 50}  Like strings, lists and tuples, sets can be iterated over using a for loop.  Example: S={10, 20, 30, 40, 50} for i in S: print(i)
  • 53. SET OPERATIONS:  1) creating sets Example: S={10, 20, 30, 40, 50} #{30, 20, 10, 40, 50}  We can use membership operator with set as Example: S={10, 20, 30, 40, 50} print(12 in S) # False print(12 not in S) # True  Set can be deleted by using del keyword Example: S={10, 20, 30, 40, 50} del S print(S) # NameError
  • 54. SET OPERATIONS: (CONT…)  It is possible to unpack a set within using *. Example: S={10, 20, 30, 40, 50} #{30, 20, 10, 40, 50} S1={100,*S,200} print(*S1)  A set can not contain a set embedded in it.  Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc.
  • 55. BUILT-IN FUNCTIONS OF SET  sum() : Calculates & Returns sum of all the elements of set.  Syntax: sum(s)  Example:  s= {1, 2, 3, 4, 5}  print(sum(s))  Note: Sum is calculated only for Numeric values, elsewise throws TypeError.  len() :Calculates & Returns number of items in a set.  Syntax: len(s)  Example:  s= {1, 2, 3, 1, 2, 1, 2, 3, 2, 1}  print(len(s))
  • 56. BUILT-IN FUNCTIONS OF SET  min() : Calculates & Returns minimum of all the elements of set.  Syntax: min(s)  Example:  s = {2.3, 4.445, 3, 5.33, 1.054, 2.5}  print(min(s))  max() :Calculates & Returns maximum of all the elements of set.  Syntax: max(s)  Example:  s= {1, 2, 3, 1, 2, 1, 2, 3, 2, 1}  print(max(s))
  • 57. BUILT-IN FUNCTIONS OF SET  sorted() : returns a sorted list of the specified set.  Syntax: sorted(set_name[,key[, Reverse_Flag ] ])  Example:  s = {2.3, 4.445, 3, 5.33, 1.054, 2.5}  l1=sorted(s)  print(l1)  l2=sorted(s, reverse=True)  print(l2) Note: if Reverse_Flag = True then sorts in descending order otherwise sort in ascending order, by default Reverse_Flag = False.
  • 58. USING ALL() BUILT-IN FUNCTIONS  This function returns true if all of the items are True (or if the iterable is empty).  All can be thought of as a sequence of AND operations on the provided iterables.  Syntax: all(s)  Example:  # print (all({True, True, True, True})) # Here all the iterables are True so all will return True and the same will be printed  print (all({False, True, True, False})) # False  print (all({False, False, False})) # False
  • 59. USING ANY() BUILT-IN FUNCTIONS  Returns true if any of the items is True.  It returns False if empty or all are false. Any can be thought of as a sequence of OR operations on the provided iterables.  Syntax: any(s)  Example:  # print (any({False, False, False, False})) # Here all the iterables are False so any will return False and the same will be printed  print (any({False, True, False, False})) # True  print (any({True, False, False, False})) # True
  • 60. SET FUNCTIONS/METHODS  add(ele):  If we want to add a single element to an existing set, we can use the .add() operation.  It adds the element to the set and returns 'None'.  If the element already exists then add() method do not add an element.  Syntax: s.add(ele) # adds element ele to set s  Example: S={10, 20, 89, 09} S.add(100) print(S) # {10, 89, 09, 100, 20} S.add(10) print(S) # {10, 89, 09, 100, 20}
  • 61. SET FUNCTIONS/METHODS  update(seq):  If we want to add a sequence of items then we use it.  seq can b a list, tuple , set or dictionary(If seq is dictionary then only keys will be added to set & not values).  It adds the elements of seq to the set and returns 'None'.  If the elements of seq already exists then .update() method do not add the elements.  Syntax: s.update(seq) # adds elements of seq to set s  Example: S={10, 20, 89, 09} S.update([100,200]) print(S) # {10, 89, 09, 100, 20} S.update((12, 13)) print(S) # {10, 89, 09, 100, 20,13,12}
  • 62. SET FUNCTIONS/METHODS  clear():  This method removes all elements of a set and return None.  Syntax: s.clear() # removes all elements of set s  Example: S={10, 20, 89, 09} S.clear() print(S) # set() print(s.clear()) # None
  • 63. SET FUNCTIONS/METHODS  remove(ele):  This method removes element ele from the set.  If element does not exist, it raises a KeyError.  The method returns None.  Syntax: s.remove(ele) # removes element ele of set s  Example: S={10, 20, 89, 09} S.remove(20) print(S) # {10, 89, 09} print(s.remove(10)) # None print(s.remove(20)) # KeyError is raised
  • 64. SET FUNCTIONS/METHODS  discard(ele):  This method also removes element ele from the set.  If element does not exist, it does not raise a KeyError. The method returns None.  Syntax: s.discard(ele) # removes element ele of set s  Example: S={10, 20, 89, 09} S.discard(20) print(S) # {10, 89, 09} print(s.discard(10)) # None print(s.discard(20)) # KeyError not raised
  • 65. SET FUNCTIONS/METHODS  pop():  This operation removes and return an arbitrary element from the set.  If there are no elements to remove, it raises a KeyError.  Syntax: s.pop() # removes arbitrary element of set s  Example: S={10, 20, 89, 09} S.pop() # arbitrary element is popped and returned. print(S) # arbitrary element which is popped print(s.pop()) # print(s.pop(20)) # KeyError raised
  • 66. SET FUNCTIONS/METHODS  copy():  The copy() method returns a shallow copy of the set.  A set can be copied using = operator in Python.  Example: S={2,35,79,0} S1=S print(S1) S1.add(100) print(S) # {35, 79, 0, 2, 100} print(S1) # {35, 79, 0, 2, 100}  Note: The problem with copying the set in this way is that if you modify the set S1, the set S is also modified.  Syntax: s.copy() # creates a shallow copy, changes made in shallow copy do not change original set.  Example: S={10, 20, 89, 09} S1=S.copy() # print(S) # print(S.copy()) # print(s.pop(20)) # KeyError raised
  • 67. SET FUNCTIONS/METHODS  __len__(): This function returns length of the object. Syntax: object.__len__() Note: object can be a list, tuple, set or dictionary. Example: S={2,35,79,0} print(S.__len__())
  • 68. MATHEMATICAL OPERATIONS : UNION  s1.union(s2) : This method returns union of set and set of elements in an iterable object s2. Sometimes, the | operator is used in place of union() method, but it operates only on the set of elements in set. Syntax: s1.union(s2)# here s2 can be set, list, tuple, dictionary or s1|s2 # here s2 must be set only. Example: s1={0,1,2,6} s2={34,54,6} print(s1.union(s2)) #{0,54,34,6,1,2,6}
  • 69. MORE EXAMPLES ON UNION  s=set(“Hacker”)  print(s.union(“Rank”))  print(s.union([„R‟,‟a‟,‟n‟,‟k‟]))  Print(s.union((„R‟,‟a‟,‟n‟,‟k‟)))  Print(s.union({“Rank”:1}))  Note: when we use dictionary as an argument to union it will add key only in a union set.  print(s|“Rank”)  print(s|[„R‟, ‟a‟, ‟n‟, ‟k‟] )  Print(s|(„R‟, ‟a‟, ‟n‟, ‟k‟))  Print(s|{“Rank”:1})  Print(s|{„R‟, ‟a‟, ‟n‟,‟ k‟})
  • 70. MATHEMATICAL OPERATIONS : INTERSECTION  s1.intersection(s2) :  The intersection() method returns the intersection of a set and the set of elements in an iterable object s2. Sometimes, the & operator is used in place of the intersection() method, but it only operates on the set of elements in set. Syntax: s1.intersection(s2)# here s2 can be set, list, tuple, dictionary or s1&s2 # here s2 must be set only. Example: s1={0,1,2,6} s2={34,54,6} print(s1.intersection(s2)) #{6}
  • 71. MORE EXAMPLES ON INTERSECTION  s=set(“Hacker”)  print(s.intersection(“Rank”))  print(s.intersection([„R‟,‟a‟,‟n‟,‟k‟]))  Print(s.intersection((„R‟,‟a‟,‟n‟,‟k‟)))  Print(s.intersection({“Rank”:1}))  Note: when we use dictionary as an argument to union it will add key only in a union set.  print(s&“Rank”)  print(s&[„R‟, ‟a‟, ‟n‟, ‟k‟] )  Print(s&(„R‟, ‟a‟, ‟n‟, ‟k‟))  Print(s&{“Rank”:1})  Print(s&{„R‟, ‟a‟, ‟n‟,‟ k‟})
  • 72. MATHEMATICAL OPERATIONS: INTERSECTION_UPDATE s1.intersection_update(s2) : This method update s1 with the intersection of s1 and s2 (iterable object) given in argument by removing the items in s1 that are not present in both s1 and s2. This method returns None Syntax: s1.intersection_update(s2) Example: >>S1={2,4,5,0} >>S2={5,0,9,8} >>print(s1.intersection_update(s2)) #None >>s1. intersection_update(s2) # >>s1 # {5,0}
  • 73. MATHEMATICAL OPERATIONS: DIFFERENCE s1.difference(s2) : The difference() returns a set with all the elements from the set that are in s1 but not in an iterable s2. Sometimes the - operator is used in place of the difference() , but it only operates on the set of elements in set. Syntax: s1.difference(s2) #here s2 can be set, list, tuple, dictionary or s1-s2 # here s2 must be set only. Example: >>S1={2,4,5,0} >>S2={5,0,9,8} >>print(s1.difference(s2)) # {2,4}
  • 74. MATHEMATICAL OPERATIONS: DIFFERENCE_UPDATE s1.difference_update(s2) : This method update s1 with the difference of s1 and s2 ( iterable object) given in argument by removing the items that exist in both sets. This method returns None Syntax: s1.difference_update(s2) Example: >>S1={2,4,5,0} >>S2={5,0,9,8} >>print(s1.intersection_update(s2)) #None >>s1. difference_update(s2) # >>s1 # {2,4}
  • 75. MATHEMATICAL OPERATIONS: SYMMETRIC_DIFFERENCE s1.symmetric_difference(s2) : Return a set that contains all items from both sets, except items that are present in both sets: Sometimes the ^ operator is used in place of the symmetric_difference() , but it only operates on the set of elements in set. Syntax: s1.symmetric_difference(s2) #here s2 can be set, list, tuple, dictionary or s1^s2 # here s2 must be set only. Example: >>S1={2,4,5,0} >>S2={5,0,9,8} >>print(s1.symmetrci_difference(s2)) # {2,4,9,8}
  • 76. MATHEMATICAL OPERATIONS : SYMMETRIC_DIFFERENCE_UPDATE s1.symmetric_difference_update(s2) : This method update s1 with the symmetric_difference()of s1 and s2 ( iterable object) This method returns None Syntax: s1.symmetric_difference_update(s2) Example: >>S1={2,4,5,0} >>S2={5,0,9,8} >>print(s1.intersection_update(s2)) #None >>s1. symmetric_difference_update(s2) # >>s1 # {2,4,9,8}
  • 77. MATHEMATICAL OPERATIONS: ISDISJOIN() s1.isdisjoint(s2) : Return True if no items in set s1 is present in set s2. Syntax: s1.isdisjoint(s2) #here s2 can be set, list, tuple, dictionary Example: >>s1={2,4,5,0} >>s2={5,0,9,8} >>print(s1.isdisjoint(s2)) # False >>s2={3,7} >> print(s1.isdisjoint(s2)) # True
  • 78. MATHEMATICAL OPERATIONS: ISSUBSET() s1.issubset(s2) : Return True if all items in set s1 are present in set s2. Sometimes the <= operator is used in place of the issubset() , but it only operates on the set of elements in set. Syntax: s1.issubset(s2) #here s2 can be set, list, tuple, dictionary Or s1 < = s2 Example: >>s1={2,4,5,0} >>s2={5,0,9,8} >>print(s1.issubset(s2)) # False >>s2={2,4,5,0,9,8} >> print(s1.issubset(s2)) # True
  • 79. MATHEMATICAL OPERATIONS: ISSUPERSET() s1.issuperset(s2) : Return True if all items in set s2 are present in set s1. Sometimes the >= operator is used in place of the issuperset() , but it only operates on the set of elements in set. Syntax: s1.issuperset(s2) #here s2 can be set, list, tuple, dictionary Or s1 > = s2 Example: >>s1={2,4,5,0} >>s2={5,0,9,8} >>print(s1.issuperset(s2)) # False >>s2={2,4,5} >> print(s1.issuperset(s2)) # True
  • 80. SET COMPREHENSION  Like list comprehensions, set comprehensions offer an easy way of creating sets. It consists of braces containing an expression followed by a for clause, and zero or more for or if clauses.  General form of set comprehension is: s={ expression for var in sequence [optional for and/or if] } Example: a={ x**2 for x in range(5) } print(a) # b={ num for num in a if num > 2 and num < 10 } print(b)
  • 81. DICTIONARY IN PYTHON : INTRODUCTION  Python dictionary is mutable and an unordered collection of items where each item of a dictionary has a key/value pair.  Each key is separated from its value by a colon (:).  The items are separated by commas, and the whole thing is enclosed in curly braces.  An empty dictionary without any items is written with just two curly braces, like this: {}.  Keys are unique within a dictionary while values may not be.  The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.  The values can be of any data type and can repeat, but keys must be of immutable type (string, number or tuple with immutable elements) and must be unique.
  • 82. DICTIONARY IN PYTHON : INTRODUCTION (CONT..)  Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.  Syntax: d={key1:value1, key2:value2,….}  Example: d={} #empty dictionary d1={1:‟one‟,4:‟four‟,9:‟nine‟} print(d1) dict = {'Name': „Xyz', 'Age': 18, 'Class': „Third'}; print("dict['Name']: ", dict['Name']) Dict = {'Name': „XYZ', 1: [1, 2, 3, 4]} print("nDictionary with the use of Mixed Keys: ") print(Dict)
  • 83. DICTIONARY : ACCESSING ELEMENTS  While indexing is used with other data types to access values, a dictionary uses keys.  Keys can be used either inside square brackets [] or with the get() method.  If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary.  On the other hand, the get() method returns None if the key is not found.  Example:  # get Vs [] for retrieving elements d={'name': „XYZ', 'age': 26} print(d['name']) # XYZ print(d.get('age')) # 26 print(d.get('address'))#None print(d['address'])#KeyError
  • 84. DICTIONARY : ITERATING USING FOR LOOP  Dictionary can be iterated over in following ways: d={'name' : 'XYZ', 'age' : 25, 'salary' : 3445} for k in d: print(k) # prints all keys of the dictionary  Iterate over key-value pairs: for x in d.items(): print(x) # prints tuples of key-value pair for k, v in d.items(): print(k, v) # prints key-value pairs  Iterate over keys: for k in d.keys(): print(k) # prints keys  Iterate over values: for v in d.values(): print(v) # prints values
  • 85. DICTIONARY : OPERATIONS  We can change the value of a specific item by referring to it‟s key name.  Example: d={'name' : 'XYZ', 'age' : 25, 'salary' : 3445} d['salary']=10000 print(d)  We can also check if key exists using membership operator.  Example: d={'name' : 'XYZ', 'age' : 25, 'salary' : 3445} if 'age' in d: print(„Yes, age is one of the key in dictionary')
  • 86. DICTIONARY : DELETING KEY FROM DICTIONARY  By using del keyword we can remove the item with the specified key name.  Example: d={'name' : 'XYZ', 'age' : 25, 'salary' : 3445} del d['salary„] print(d)  We can also delete the complete dictionary using del keyword.  Example: d={'name' : 'XYZ', 'age' : 25, 'salary' : 3445} del d print(d) # NameError: name 'd' is not defined
  • 87. DICTIONARY : BUILT-IN METHODS  Consider, d={1:'one', 4:‘four', 9:‘nine'}  sum() : calculate and return sum of all keys of d if keys are numeric.  Example: print(sum(d)) #14  min() : returns minimum of all keys in d.  Example: print(min(d)) # 1  max() : returns maximum of all keys in d.  Example: print(max(d)) # 9  len() : returns number of key - value pairs.  Example : print(len(d)) # 3  sorted() : returns list by sorting the dictionary in ascending order based on keys.  Example : print(sorted(d)) # [1,4,9]
  • 88. DICTIONARY : METHODS  Consider, d={8:‘eight', 4:‘four', 9:‘nine'}  Clear(): Removes all the elements from the dictionary. It returns None  Syntax: d.clear()  Example: d.clear() # d is dictionary print(d) #{}  Copy(): Returns a copy of the dictionary.  Syntax: d.copy()  Example:  d1=d.copy()  d[8]=„example‟  print(d)#  print(d1)#
  • 89. DICTIONARY : METHODS  Consider, d={8:‘eight', 4:‘four', 9:‘nine'}  fromkeys(): Returns a dictionary with the specified keys and a value.  Syntax: dict.fromkeys(seq [, value])  Note:Value is optional, if not provided None will be added as value.  Example: d={} x={„a‟, „v‟, „k‟} d1=d.fromkeys(x) # print(d1) # d1={„a‟:None, „v‟: None,‟k‟:None} y=10 d2=d.fromkeys(x, y) print(d2) # d1={„a‟:10, „v‟: 10, ‟k‟ :10} z=[1,2] d3= d.fromkeys(x, z) print(d3) # d1={„a‟:[1, 2], „v‟: [1, 2], ‟k‟ :[1, 2]}
  • 90. DICTIONARY : METHODS  Consider, d={8:‘eight', 4:‘four', 9:‘nine'}  get(): The get() method returns the value of the item with the specified key.  Syntax: d.get(key [,value])  Note:Value is optional, A value to return if the specified key does not exist. Default value None.  Example: x=d.get(8,‟xyz‟) print(x) y=d.get(7,‟abc‟) print(y)
  • 91. DICTIONARY : METHODS  Consider, d={8:‘eight', 4:‘four', 9:‘nine'}  items(): The items() method returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list.  The view object will reflect any changes done to the dictionary, see example below.  Syntax: d.items() #where d is dictionary.  Example: x=d.items() print(x) d[8]=„xyz‟ print(d) print(x)
  • 92. DICTIONARY : METHODS  Consider, d={8:‘eight', 4:‘four', 9:‘nine'}  keys(): The keys() method returns a view object. The view object contains the keys of the dictionary, as a list.  The view object will reflect any changes done to the dictionary, see example below.  Syntax: d.keys() #where d is dictionary.  Example: x=d.keys() print(x) d[1]=„one‟ print(d) print(x)
  • 93. DICTIONARY : METHODS  Consider, d={8:‘eight', 4:‘four', 9:‘nine'}  pop(): The pop() method removes the specified item from the dictionary.  The value of the removed item is the return value of the pop() method.  Syntax: d.pop(key [,defaultValue]) #where d is dictionary.  Note: Optional. A value to return if the specified key do not exist.  Example: print(d.pop(8,‟hello‟))#eight print(d.pop(1,‟hello‟)) #hello print(d.pop(2))# KeyError
  • 94. DICTIONARY : METHODS  Consider, d={8:‘eight', 4:‘four', 9:‘nine'}  popitem(): method removes the item that was last inserted into the dictionary.  The removed item is the return value of the popitem() method, as a tuple  Syntax: d.popitem() #where d is dictionary.  Example: print(d.popitem())#
  • 95. DICTIONARY : METHODS  Consider, d={8:‘eight', 4:‘four', 9:‘nine'}  setdefault(): The setdefault() method returns the value of the item with the specified key.  If the key does not exist, insert the key, with the specified value.  Syntax: d.setdefault(key [,value]) #where d is dictionary.  Note: Value is Optional. If the key exist, this parameter has no effect. If the key does not exist, this value becomes the key's value. Default value None  Example: print(d.setdefault(8,‟hello‟))#eight print(d.setdefault(1,‟hello‟)#inserts 1:hello & return hello Print(d.setdefault(2)#None
  • 96. DICTIONARY : METHODS  Consider, d={8:‘eight', 4:‘four', 9:‘nine'}  update(): The update() method inserts the specified items to the dictionary. It returns None.  The specified items can be a dictionary, or an iterable object with key value pairs.  Syntax: d.update(iterable) #where d is dictionary.  Example: d.update([(2,‟two‟),(3,‟three‟)]) print(d)# d.update(((4,‟two‟),(5,‟three‟))) print(d) d.update({0:‟zero‟,6:‟six‟}) print(d)
  • 97. DICTIONARY : METHODS  Consider, d={8:‘eight', 4:‘four', 9:‘nine'}  values(): The values() method returns a view object. The view object contains the values of the dictionary, as a list.  The view object will reflect any changes done to the dictionary.  Syntax: d.values() #where d is dictionary.  Example: X=d.values() print(X) d[8]=„example‟ # Changes will be reflected in X also. print(d) print(X) #
  • 98. DICTIONARY : METHODS  Consider, d={8:‘eight', 4:‘four', 9:‘nine'}  __len__(): The __len__() method returns length of dictionary.  Syntax: d.__len__() #where d is dictionary.  Example: X=d.__len__() print(X)
  • 99. NESTED DICTIONARY:  Dictionary within dictionary is called nested dictionary is called nested dictionary.  Example: Employee={ 'xyz': {'dob':'23/12/2020','age':23}, 'abc': {'dob':'13/04/2021','age':20}, 'pqr': {'dob':'21/02/2019','age':18} } print(Employee)
  • 100. ITERATING OVER NESTED DICTIONARY: for i,j in Employee.items(): print(i,j) for i in Employee.items(): print(i) for i in Employee.keys(): print(i) for i in Employee.values(): print(i)
  • 101. Dictionary Comprehension General form is: d={key:value for (key,value) in d.items()}  Example: d={„a‟:1,‟b‟:2,‟c‟:3,‟d‟:4,‟e‟:5} #Obtain dictionary with each value cubed d1={k:v**3 for (k,v) in d.items()} print(d1)#dictionary with each value cubed #obtain dictionary with each value cubed if value>3 d2={k:v for (k,v) in d.items() if v>3} print(d2) #Identify odd and even entries in the dictionary d3={k:(„EVEN‟ if v%2==0 else „ODD‟) for (k,v) in d.items()}
  • 102. Dictionary Comprehension  Create two lists students and marks. Create a dictionary from these two lists using dictionary comprehension. Use names as keys and marks as values.  Answer: lstnames=[„Sunil‟,‟Anuj‟,‟Rahul‟,‟Anuja‟,‟Rohit‟] lstmarks=[54,65,45,67,78] d={k:v for (k,v) in zip(lstnames,lstmarks)} print(d)
  • 103. Problem Statement: 01  Write a program that reads a string from the keyboard and creates dictionary containing frequency of each character occuring in the string.
  • 104. Problem Statement: 02  A sparse matrix is a matrix most of whose elements have a value 0. Suppose we have a 5x5 sparse matrix stored as a list of lists. Dictionary should store the row and column of a non-zero element as a tuple key and the value of the non- zero element as the value against the key tuple.
  • 105. Problem Statement: 03  Given the following dictionary:  Marks={„subu‟:{„Math‟:88,‟Eng‟:60,‟Sst‟:95}, „Amol‟:{„Math‟:78,‟Eng‟:68,‟Sst‟:89}, „Rama‟:{„Math‟:68,‟Eng‟:66,‟Sst‟:87}, „Raka‟:{„Math‟:88,‟Eng‟:68,‟Sst‟:95}} Write a program to perform the following operations: a) Print marks obtained by amol in English b) Set marks obtained by Rama in Maths to 77 c) Sort the dictionary by name
  • 106. Problem Statement: 04  Create a dictionary which stores following data: Interface IP Address status Eth0 1.1.1.1 up Eth1 2.2.2.2 up Wlan0 3.3.3.3 down Wlan1 4.4.4.4 up  Write a program to perform following operations: a) Find the status of a given interface b) Find Interface and IP of all interfaces which are up. c) Find the total number of interfaces d) Add two new entries to the dictionary.