Data_Structure&STR
Data_Structure&STR
Python provide Collection types and each collection type uses one data
structure to organize data.
Collections allows to group and refer objects with one name. Collections
efficient because these follows some rules and regulations for storing and
reading objects.
Types of collections
1. Sequences
a. List
b. Tuple
c. Range
d. String
e. Bytes
f. Bytesarray
2. Non Sequences
a. Set
b. Frozenset
c. Dict
List
>>> list1=[]
>>> list1
[]
>>> type(list1)
<class 'list'>
>>> list1=[10,20,30,40,50]
>>> list1
>>> type(list1)
<class 'list'>
>>> student_info=[101,'naresh','python',4000]
>>> student_info
>>> type(student_info)
<class 'list'>
>>> list3=list()
>>> list3
[]
>>> type(list3)
<class 'list'>
>>> list4=list([10,20,30,40,50])
>>> list4
>>> list5=list(range(1,11,1))
>>> list5
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>
List is index based collection, where reading and writing is done using
index.
list1=[10,20,30,40,50]
print(list1[0])
print(list1[1])
print(list1[2])
print(list1[3])
print(list1[4])
print(list1[index])
print(list1[index])
print(list1[index])
Syntax: len(collection/iterable)
list1=[10,20,30,40,50]
s=0
print(f'Sum is {s}')
1. Index
2. Slicing
3. For loop
4. Iterator
5. Enumerate
Python allows to read items/objects from list in different ways.
1. Index
2. Slicing
3. For loop
4. Iterator
5. Enumerate
Index is used to read and write items of list, it allows to read and write
items sequentially and randomly. Using index we can read or write
only one item.
Example:
list1=[10,20,30,40,50]
print(list1[0])
print(list1[1])
print(list1[4])
print(list1)
print(list1)
del list1[2]
print(list1)
1. Slice operator
2. Slice object
Slice Operator
Sequence-name[startindex:stopindex:step]
Example:
list1=list(range(10,110,10))
print(list1)
list2=list1[::] # start=0,stop=len(list1),step=+1
list3=list1[:] # start=0,stop=len(list1),step=+1
print(list2)
print(list3)
list4=list1[::-1] # start=-1,stop=-len(list1)+1,step=-1
list5=list1[::-2] # start=-1,stop=-len(list1)+1,step=-2
print(list4)
print(list5)
list6=list1[::2] # start=0,stop=len(list1),step=+2
print(list6)
Example:
list1=list("PROGRAMMING")
print(list1)
list2=list(range(10,110,10))
print(list2)
list3=[10,20,30,40,50]
print(list3)
Example:
list1=list(range(1,11,1))
print(list1)
list2=list1[::2]
list3=list1[::-2]
print(list2)
print(list3)
list4=list1[0:6:2]
list5=list1[-1:-8:-2]
print(list4)
print(list5)
list6=list1[len(list1)-1::-1] # list1[9::-1]
list7=list1[-len(list1)::1] # list1[-10::1]
print(list6)
print(list7)
Slice object
Slice object is reusable. We create slice object with start, stop and
step. This object can be applied to one or more than one sequence.
slice(start,stop,[step])
slice(stop)
Exmaple
list1=[10,20,30,40,50,60,70,80,90,100]
list2=[1,2,3,4,5,6,7,8,9,10]
list3=[2,4,6,8,10,12,14,16,18,20]
s=slice(0,5)
list4=list1[s]
list5=list2[s]
list6=list3[s]
print(list1)
print(list2)
print(list3)
print(list4)
print(list5)
print(list6)
Iterator
iter(iterable)
Iterator is read only cursor, it allows to read from underlying sequence but
does not allows modify.
iter(iterable)
course_list=['java','python','.net','c','c++']
x=iter(course_list)
c1=next(x)
c2=next(x)
c3=next(x)
c4=next(x)
c5=next(x)
print(c1,c2,c3,c4,c5)
c6=next(x) # error
Iterator is given to for loop, so that it can read each time one value.
For loop internally calls next() function of iterator, which return next
value from iterable.
list1=list(range(10,110,10))
print(list1)
e=iter(list1)
e1=next(e)
e2=next(e)
print(e1,e2)
for x in e: # next(e)
print(x)
Enumerate
Enumerate is a cursor which is used to read elements from
iterables(collections). Enumerate return two values 1. Index 2. Value
This is useful in construction of dictionary object.
Syntax:
enumerate(iterable)
list1=[10,20,30,40,50]
x=enumerate(list1)
e1=next(x)
e2=next(x)
print(e1)
print(e2)
for e in x:
print(e)
for loop
for loop is used to read elements from iterables or sequences. For loop
internally create iterator on iterable and calls next() function.
Syntax:
for loop each time read one value from iterable and execute statements.
This repeating is done until all the elements read from iterable.
list1=[10,20,30,40,50]
for e in list1:
print(e)
Mutable Operations of List
List is a mutable sequence. After creating list we can add, update and
delete items.
Example:
list1=[]
list1.append(10)
list1.append(20)
list1.append(30)
list1.append(40)
for value in list1:
print(value)
Exmaple:
# write a program to read scores of n players and display
scores=[]
n=int(input("enter how many players")) # 3
for i in range(n): # 0 1 2
s=int(input("enter score"))
scores.append(s)
for score in scores:
print(score)
Example:
# write a program to read n integers into list
# after reading separate even no into even list
# odd numbers into odd list
numbers=[]
n=int(input("Enter how many numbers"))
for i in range(n):
num=int(input("enter any number"))
numbers.append(num)
enumbers=[]
onumbers=[]
print(numbers)
print(enumbers)
print(onumbers)
Example:
# write a program to read name and n subjects marks
# display total and avg
name=input("enter name")
n=int(input("enter how many subject marks"))
marks=[]
for i in range(n):
s=int(input("enter marks"))
marks.append(s)
total=sum(marks)
avg=total/n
print(name)
print(marks)
print(total)
print(avg)
extends s with the contents of t (for the most part
s.extend(t) or s += t
the same as s[len(s):len(s)] = t)
Example
list1=[10,20,30,40,50]
list2=[60,70,80]
print(list1)
print(list2)
list1.extend(list2)
print(list1)
Example
list1=[1,2,3,4,5]
list2=[6,7,8,9,10]
list1[len(list1):len(list1)]=list2
print(list1)
Example
python_batch1=['suresh','kishore','naresh']
python_batch2=['kiran','ramesh','rajesh','abhishek']
python_batch1.extend(python_batch2)
print(python_batch1)
list1=[10,20,30,40,50]
list1.insert(1,60)
print(list1) # [10,60,20,30,40,50]
list1.insert(0,90)
print(list1)
Example
list1=[100,200,300,400,500]
list2=[600,700,800]
list1[2:2]=list2
print(list1)
Explanation: insert method of list insert only one object at given index.
List-name.insert(index,value)
In order to insert more than one value at given position we use slicing.
List-name[start-index:stop-index]
List1=[100,200,300,400,500]
List1[1:1]=[1000,2000,3000]
Example
list1=[10,20,30,40,50]
print(list1)
list1[1]=60
print(list1)
Example
list1=[10,20,30,40,50]
list1[1:4]=[100,200,300]
print(list1)
Slice uses range for generating values. Stop index is not included.
Example
list1=[1,2,3,4,5,6,7,8,9,10]
list2=[10,20,30,40,50]
list1[0::2]=list2
print(list1)
Example
list1=list(range(10,110,10))
print(list1)
list1[-1::-1]=range(1,11)
print(list1)
Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Example
list1=[10,20,30,40,50]
del list1[0]
print(list1)
On deletion of element, the elements which are at right side shifted towards
left side. In above example 10 element is deleted using index 0. After
deleting 20,30,40,50 are shifted one position left side.
Deleting Elements from list
Example
list1=[10,20,30,40,50]
del list1[0]
print(list1)
On deletion of element, the elements which are at right side shifted towards
left side. In above example 10 element is deleted using index 0. After
deleting 20,30,40,50 are shifted one position left side.
Example
list1=[10,20,30,40,50,60,70,80,90,100]
print(list1)
del list1[8] # using index we can delete one element
print(list1)
del list1[1:4] # using slicing we can delete more than one element
print(list1)
Output:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
[10, 20, 30, 40, 50, 60, 70, 80, 100]
[10, 50, 60, 70, 80, 100]
Example
list1=list(range(10,110,10))
print(list1)
del list1[1::2] # delete all elements from 1 to till the end of list
# by incrementing index with 2
print(list1)
list2=list(range(1,11))
print(list2)
del list2[-1:-5:-1] # delete all elements from -1 to -4
print(list2)
Output:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
[10, 30, 50, 70, 90]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6]
Example
Remove Method of list, its remove value/element from list using value but
not using index.
list1=[10,20,30,40,50]
print(list1)
list1.remove(20)
print(list1)
list1.remove(100)
Output:
[10, 20, 30, 40, 50]
[10, 30, 40, 50]
Traceback (most recent call last):
list1.remove(100)
names_list=[]
for i in range(n):
name=input("enter name")
names_list.append(name)
print(names_list)
if name in names_list:
names_list.remove(name)
print("name deleted")
else:
print(names_list)
Output:
enter namesuresh
enter namerajesh
enter namenaresh
name deleted
['rajesh', 'naresh']
Removing all the elements or values can be done using clear method.
list1=[10,20,30,40,50]
list1.clear()
print(list1)
list2=[10,20,30,40,50]
list2[:]=[] # updating list2 with empty list
print(list2)
***MENU***
1. Add
2. Updating
3. Removing
4. View
5. Exit
website_list=[]
while True:
print("***MENU****")
print("1. Add")
print("2. Update")
print("3. Remove")
print("4. View")
print("5. Exit")
if opt==1:
website_list.append(site_name)
elif opt==2:
if site_name in website_list:
i=website_list.index(site_name)
website_list[i]=nsite_name
elif opt==3:
if site_name in website_list:
website_list.remove(site_name)
else:
elif opt==4:
print(name)
elif opt==5:
break
else:
print("invalid option")
Using list as Stack
Stack is data structure which follows LIFO (Last In First Output) approach.
The element which is inserted last is removed first.
In python stack can be implemented using List.
Stack Operations
1. Push
2. Pop
3. Exit
Enter your option
stack=[]
while True:
print("***Stack Operations***")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
opt=int(input("Enter your option"))
if opt==1:
ele=int(input("enter element"))
stack.append(ele)
print("element pushed inside stack")
elif opt==2:
if len(stack)==0:
print("stack is empty")
else:
ele=stack.pop()
print(ele,"is poped from stack")
elif opt==3:
print(stack)
elif opt==4:
break
Queue Operations
1. Adding Element
2. Removing Element
3. Display Queue
4. Exit
Enter Your option
queue=[]
while True:
print("Queue Operations")
print("1. Adding Element")
print("2. Removing Element")
print("3. Display")
print("4. Exit")
opt=int(input("Enter your option"))
if opt==1:
ele=int(input("enter element"))
queue.append(ele)
print("element is added into queue")
elif opt==2:
if len(queue)==0:
print("Queue is empty")
else:
ele=queue[0]
del queue[0]
print(ele,"is removed from queue")
elif opt==3:
print(queue)
elif opt==4:
break
Types of copy
1. Shallow Copy
2. Deep Copy
Shallow Copy : Shallow copy is reference copy. It will copy addresses of
objects from one sequence(list) to another sequence(list).
Deep Copy : deep copy is object copy, it will create copy of object and
store into another sequence or list. In order to perform deep copy import
one module called copy. This module is having deepcopy function, this will
create deepcopy of sequence or list.
Import copy
Example of shallow copy
list1=[10,20,30,40,50]
list2=list1.copy() # shallow copy
print(list1)
print(list2)
list3=[[10,20]]
list4=list3.copy()
print(list3)
print(list4)
list3[0].append(30)
print(list3)
print(list4)
import copy
list1=[[10,20]]
list2=copy.deepcopy(list1)
print(list1)
print(list2)
list1[0].append(30)
print(list1)
print(list2)
Nested List
List within list is called nested list. Nested list can be used as matrices.
In Nested list data is organized in multiple rows and columns.
Nested list elements are identified with row index and column index. This
index can be +ve or –ve
print(list1[-1][-1],list1[-1][-2])
print(list1[-2][-1],list1[-2][-2])
print(list1[-3][-1],list1[-3][-2])
students=[]
m=int(input("enter how many classes")) #5
for i in range(m):
students.append([])
n=int(input("enter how many students"))
for j in range(n):
name=input("enter name")
students[i].append(name)
for i in range(m):
matrix3.append([])
for j in range(n):
matrix3[i].append(matrix1[i][j]+matrix2[i][j])
print(matrix1)
print(matrix2)
print(matrix3)
List Comprehension
1st approach
list1=[10,20,30,40,50,60]
list2=[10+20,1+2,3+4,5+6]
Syntax1:
Example
names_list=['naresh','suresh','kishore','rajesh','ramesh']
names_list1=[name.upper() for name in names_list]
names_list2=[name.title() for name in names_list]
names_list3=[name.lower() for name in names_list]
# without comprehension
list1=[]
for name in names_list:
list1.append(name.upper())
print(names_list)
print(names_list1)
print(names_list2)
print(names_list3)
Example
list1=list(range(1,11))
print(list1)
list2=[chr(n) for n in range(65,91)]
list3=[chr(n) for n in range(97,123)]
print(list1)
print(list2)
print(list3)
list4=[]
for n in range(65,91):
list3.append(chr(n))
print(list4)
Syntax-2: list-name=[expression for variable in iterable if test]
1. For loop read each time one value from iterable.
2. After reading value test condition, if condition is True
3. Eval expression and result is stored into the list
Example
sales_list=[15000,20000,12000,14000,25000,11000]
sales_list1=[sale for sale in sales_list if sale>=15000]
sales_list2=[sale for sale in sales_list if sale<15000]
print(sales_list)
print(sales_list1)
print(sales_list2)
Example
numbers_list=[1,2,3,5,7,8,11,12,13,14,27,29,25,23]
numbers_list1=[num for num in numbers_list if num%2==0]
numbers_list2=[num for num in numbers_list if num%2!=0]
print(numbers_list)
print(numbers_list1)
print(numbers_list2)
Example:
list_str=['abc','XYZ','pqr','MNO','jkl','fgh','WQER']
list_str1=[s for s in list_str if s.isupper()]
list_str2=[s for s in list_str if s.islower()]
print(list_str)
print(list_str1)
print(list_str2)
Example
list1=["abc","123","a123","xyz","x456","789"]
list2=[value for value in list1 if value.isalpha()]
list3=[value for value in list1 if value.isalnum()]
list4=[value for value in list1 if value.isdecimal()]
print(list1)
print(list2)
print(list3)
print(list4)
matrix1=[[1,2],[3,4]]
matrix2=[[5,6],[7,8]]
# without list comprehension
matrix3=[]
for i in range(2):
matrix3.append([])
for j in range(2):
matrix3[i].append(matrix1[i][j]+matrix2[i][j])
# list comprehension
matrix4=[[matrix1[i][j]+matrix2[i][j] for j in range(2)] for i in range(2)]
print(matrix1)
print(matrix2)
print(matrix3)
print(matrix4)
Syntax -3: Nested for loop
Without Comprehension:
print(list1)
print(list2)
# with comprehension
list3=[col for row in list1 for col in row]
print(list3)
student_list=[['naresh',50,60],['suresh',80,90],['kishore',30,50]]
student_fail_list=[stud[0] for stud in student_list if stud[1]<40 or stud[2]<40]
print(student_list)
print(student_fail_list)
Tuple
Tuple is a list or sequence or iterable.
Tuple is a immutable sequence. Once the tuple is created we cannot
modify(add,update or delete).
Tuples are immutable sequences, typically used to store collections of
heterogeneous data.
Tuples are also used for cases where an immutable sequence of
homogeneous data is needed (such as allowing storage in a set or dict
instance).
>>> t1=10,
>>> type(t1)
<class 'tuple'>
>>> t2=(100,)
>>> type(t2)
<class 'tuple'>
>>> t3=1000,2000,300
>>> type(t3)
<class 'tuple'>
>>> t4=(1,2,3,4,5)
>>> type(t4)
<class 'tuple'>
>>> l1=[10,20,30]
>>> l1
[10, 20, 30]
>>> l1[0]=100
>>> l1
[100, 20, 30]
>>> t1=(10,20,30)
>>> t1[0]=100
Traceback (most recent call last):
File "<pyshell#44>", line 1, in <module>
t1[0]=100
TypeError: 'tuple' object does not support item assignment
>>>
>>> del l1[0]
>>> l1
[20, 30]
>>> del t1[0]
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
del t1[0]
TypeError: 'tuple' object doesn't support item deletion
>>>
>>> l1.append(90)
>>> l1
[20, 30, 90]
>>> t1.append(90)
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
t1.append(90)
AttributeError: 'tuple' object has no attribute 'append'
>>>
Example:
t1=(10,20,30,40,50)
t2=tuple(range(10,60,10))
i=iter(t1)
print(next(i))
print(next(i))
# reading elements of tuple using for loop
e=enumerate(t1)
print(next(e))
print(next(e))
List 10 20 30 40 50 60
Set 10 20 30 40 50 60 orders of insertion are done using one data
structure called hashing.
>>> a={}
>>> type(a)
<class 'dict'>
>>> b={10}
>>> type(b)
<class 'set'>
>>> c=set()
>>> d=set([10,20,30,40,50])
>>> c
set()
>>> d
{40, 10, 50, 20, 30}
2. update() : This method is used to add more than one element into set
set1=set()
set1.add(10)
set1.add(20)
print(set1)
set1.update({30,40,50})
print(set1)
set1.update([10,20,30,40,50,60,70,80])
print(set1)
set1.update("PYTHON")
print(set1)
set1.update(range(100,110))
print(set1)
set1={10,20,30,40,50}
print(set1)
set1.remove(20)
print(set1)
set1.remove(40)
print(set1)
Input: java
Ouput:1j2a1v
Set Operations
1. update(*others)
set |= other | ...
Update the set, adding elements from all others.
Example:
emp_dept10={'naresh','suresh','kishore'}
emp_dept20={'ramesh','rajesh','rakesh'}
print(emp_dept10)
print(emp_dept20)
emp_dept10.update(emp_dept20)
print(emp_dept10)
Example
s1={1,2,3,4,5}
s2={6,7,8}
s1|=s2
print(s1)
2. union(*others)
set | other | ...
Return a new set with elements from the set and all others.
Example
emp_deptno10={'naresh','suresh'}
emp_deptno20={'rajesh','rakesh'}
emp_deptno1020=emp_deptno10.union(emp_deptno20)
print(emp_deptno10)
print(emp_deptno20)
print(emp_deptno1020)
Example
s1={1,2,3,4,5}
s2={1,2,6,7,8}
s3=s1|s2
print(s1)
print(s2)
print(s3)
set1={10,20}
set2={30,40}
set1.update(set2)
print(set1)
print(set2)
3. intersection(*others)
set & other & ...
Return a new set with elements common to the set and all others.
1. intersection(*others)
set & other & ...
Return a new set with elements common to the set and all others.
Example
set1={10,20,30,40,50}
set2={10,20,30,60,70}
set3=set1.intersection(set2)
print(set1)
print(set2)
print(set3)
set4=set1&set2
print(set4)
s1={1,2,3,4,5}
s2={1,2,6,7,8}
s3={2,3,4,5,6}
s4=s1&s2&s3
print(s1)
print(s2)
print(s3)
print(s4)
Example
python_set={'naresh','suresh','kishore'}
java_set={'suresh','ramesh','rajesh'}
python_java_set=python_set.intersection(java_set)
print(python_set)
print(java_set)
print(python_java_set)
2. difference(*others)
set - other - ...
Return a new set with elements in the set that are not in the others
Example
maths_result={'suresh','naresh','kishore','ramesh','rajesh'}
science_result={'suresh','naresh','kishore','amar','mahesh'}
only_maths=maths_result.difference(science_result)
print(only_maths)
only_science=science_result.difference(maths_result)
print(only_science)
maths_science=maths_result.intersection(science_result)
print(maths_science)
Example
set1={1,2,3,4,5}
set2={1,2,3,6,7}
set3=set1.difference(set2)
print(set1)
print(set2)
print(set3)
Example
s1={1,2,3,4,5}
s2={1,2,3,6,7}
s3={1,2,3,4,7}
s4=s1-s2-s3
print(s1)
print(s2)
print(s3)
print(s4)
3. symmetric_difference(other)
set ^ other
Return a new set with elements in either the set or other but not both.
Example
s1={1,2,3,4,5}
s2={1,2,3,6,7}
s3=s1.symmetric_difference(s2)
print(s1)
print(s2)
print(s3)
s4=s1^s2
print(s4)
Example
set1={'a','b','c','d','e'}
set2={'a','b','f','g','h'}
set3=set1.symmetric_difference(set2)
print(set1)
print(set2)
print(set3)
Example
python_set={'naresh','suresh','kishore','rajesh','sai'}
java_set={'ramesh','rajesh','kiran','naresh','amar'}
only_java_python=python_set^java_set
print(python_set)
print(java_set)
print(only_java_python)
Example
s1={1,2,3,4,5}
s2={1,2,3,6,7}
s3={1,2,3,8,9}
s4=(s1|s2)-(s1|s3)
print(s1)
print(s2)
print(s3)
print(s4)
Example
A={1,2,3,4,5}
B={1,4,5,6,7}
C={2,3,4,8,9}
D=(A|B)&C
print(A)
print(B)
print(C)
print(D)
4. isdisjoint(other)
Return True if the set has no elements in common with other. Sets
are disjoint if and only if their intersection is the empty set.
5. issubset(other)
set <= other
Test whether every element in the set is in other.
6. issuperset(other)
set >= other
Test whether every element in other is in the set.
Example
A={1,2,3,4,5}
B={1,2,3,4,5}
x=A.isdisjoint(B)
print(A)
print(B)
print(x)
S1={1,2,3}
S2={4,5,6}
y=S1.isdisjoint(S2)
print(S1)
print(S2)
print(y)
Example
C={'datatypes','functions','structures'}
CPP={'datatypes','functions','structures','classes','objects'}
if CPP.issuperset(C):
print('C++ is superset of C langauge')
else:
print("C++ is not super set of C language")
Example
C={'datatypes','functions','structures'}
CPP={'datatypes','functions','structures','classes','objects'}
if C.issubset(CPP):
print('C is subset of CPP langauge')
else:
print("C is not suB set of CPP language")
Update methods
update(*others)
set |= other | ...
intersection_update(*others)
set &= other & ...
Update the set, keeping only elements found in it and all others.
difference_update(*others)
set -= other | ...
Update the set, keeping only elements found in either set, but not in
both.
A={10}
B={20}
A|=B
Functions which are used on the set.
any() : Return True if any element of the iterable is true. If the iterable is
empty, return False
>>> set1={10,20,30,40,50}
>>> any(set1)
True
>>> set2={False}
>>> any(set2)
False
>>> list1=[False,True]
>>> any(list1)
True
>>> list2=[0,0,0,0,0]
>>> any(list2)
False
>>> set2=set()
>>> any(set2)
False
>>> list2=[]
>>> any(list2)
False
>>>
all(iterable)
Return True if all elements of the iterable are true (or if the iterable is
empty).
>>> l1=[True,False,True]
>>> all(l1)
False
>>> l2=[True,True]
>>> all(l2)
True
>>> s1={True}
>>> all(s1)
True
>>> s2=set()
>>> all(s2)
True
Frozenset
Frozenset is a set.
Forzenset is immutable set. After creating frozenset we cannot do any
changes(add,remove).
Forzenset is hashble type, in application development in order to represent
nested sets or sets with sets we use frozenset.
Syntax:
frozenset([iterable]) : this create frozenset using values from iterable.
If iterable is not supplied it will create empty forzenset.
>>> set1={{1,2,3},{4,5,6}}
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
set1={{1,2,3},{4,5,6}}
TypeError: unhashable type: 'set'
>>> fs1=frozenset()
>>> fs1.add(10)
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
fs1.add(10)
AttributeError: 'frozenset' object has no attribute 'add'
>>> s1=set()
>>> s1.add(10)
>>> s1
{10}
>>> fs2=frozenset(range(10,110,10))
>>> fs2
frozenset({100, 70, 40, 10, 80, 50, 20, 90, 60, 30})
>>> fs2=frozenset(['a','b','c','d','e'])
>>> fs2
frozenset({'c', 'd', 'e', 'b', 'a'})
>>> fs3=frozenset((1,2,3,4,5))
>>> fs3
frozenset({1, 2, 3, 4, 5})
>>> fs4=frozenset({10,20,30,40,50})
>>> fs4
frozenset({50, 20, 40, 10, 30})
>>>
Example
set1={frozenset({1,2,3,4,5}),frozenset({1,2,3,4,5})}
print(set1)
set2={frozenset({1,2,3,4,5}),frozenset({6,7,8,9})}
print(set2)
set3={frozenset({1,2,3,4,5}),frozenset({1,2,3,8,9})}
print(set3)
Example
set1={frozenset([10,20,30]),frozenset([40,50,60])}
print(set1)
for s in set1:
for value in s:
print(value,end=' ')
print()
i=iter(set1)
s1=next(i)
s2=next(i)
print(s1)
print(s2)
for value in s1:
print(value,end=' ')
Example
python_set={'naresh','suresh','kishore'}
java_set={'suresh','kiran','ramesh','rajesh'}
student_set={frozenset(python_set),frozenset(java_set)}
print(student_set)
Dictionary Is a map collection, where the data is stored as key and value.
Duplicate keys are not allowed but duplicate values are allowed. One key is
mapped with one or more than one value.
Dictionary is a key based collection, where reading and writing is done
using key. Dictionary is mutable collection.
1. We can create dictionary using curly braces {}, this create empty
dictionary.
>>> d1={}
>>> type(d1)
<class 'dict'>
>>> d1
{}
>>>
>>> d1=dict()
>>> d1
{}
>>> type(d1)
<class 'dict'>
>>> list1=[(1,100),(2,200),(3,300),(4,400),(5,500)]
>>> d1=dict(list1)
>>> d1
{1: 100, 2: 200, 3: 300, 4: 400, 5: 500}
>>>
>>> d2={1:100,2:200,3:300,4:400,5:500}
>>> d3=dict(d2)
>>> d2
{1: 100, 2: 200, 3: 300, 4: 400, 5: 500}
>>> d3
{1: 100, 2: 200, 3: 300, 4: 400, 5: 500}
zip(): Make an iterator that aggregates elements from each of the iterables
Returns an iterator of tuples, where the i-th tuple contains the i-th element
from each of the argument sequences or iterables. The iterator stops when
the shortest input iterable is exhausted.
>>> d4=dict(zip(range(1,6),range(10,60,10)))
>>> d4
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
>>> names_list=['naresh','suresh','kishore','ramesh']
>>> course_list=['python','oracle','cpp','java']
>>> student_dict=dict(zip(names_list,course_list))
>>> student_dict
{'naresh': 'python', 'suresh': 'oracle', 'kishore': 'cpp', 'ramesh': 'java'}
>>>
>>> str1="PYTHON"
>>> str2="PYTHON"
>>> d5=dict(zip(str1,str2))
>>> d5
{'P': 'P', 'Y': 'Y', 'T': 'T', 'H': 'H', 'O': 'O', 'N': 'N'}
>>> rno=[101,102,103]
>>> names=['ramesh','kishore','naresh']
>>> d6=dict(zip(rno,names))
>>> d6
{101: 'ramesh', 102: 'kishore', 103: 'naresh'}
>>>
How to read content from dictionary?
Example:
product_dict={'mouse':200,'keyboard':2000,'monitor':3000}
print(product_dict['mouse'])
print(product_dict['keyboard'])
print(product_dict['monitor'])
print(product_dict['usb'])# KeyError
Example:
d1={1:100,2:200,3:300,4:400,5:500}
x=iter(d1)
print(next(x)) # return key 1
print(next(x)) # return key 2
print(next(x)) # return key 3
print(next(x))
print(next(x))
y=iter(d1)
key1=next(y)
value1=d1[key1]
key2=next(y)
value2=d1[key2]
print(key1,value1)
print(key2,value2)
z=iter(d1)
for key in z:
print(key,d1[key])
items()
Example
dict1={1:100,2:200,3:300,4:400,5:500}
x=dict1.items()
print(type(x))
i=iter(x)
item1=next(i)
print(item1)
item2=next(i)
print(item2)
item3=next(i)
print(item3)
item4=next(i)
print(item4)
Example
dict1={1:100,2:200,3:300,4:400,5:500}
x=dict1.items()
for item in x:
print(item)
Example
dict1={1:100,2:200,3:300,4:400,5:500}
for item in dict1.items():
k,v=item # unpacking (1,100)
print(k,v)
keys()
dict_courses={'python':4000,'java':2000,'oracle':1000}
courses=dict_courses.keys()
for course in courses:
print(course)
values()
dict_mailid={'naresh':'naresh.it@gamilcom','suresh':'[email protected]'}
emailid=dict_mailid.values()
for email in emailid:
print(email)
student_dict={}
while True:
rollno=int(input("enter rollno"))
name=input("enter name")
if rollno in student_dict:
print("duplicate keys are not allowed")
else:
student_dict[rollno]=name
ans=input("Add another student?")
if ans=="no":
break
Example
# program which perform two operations
# 1 adding items 2. updating items
products={}
while True:
print("1. Add product")
print("2. Update product")
print("3. Exit")
opt=int(input("enter your option"))
if opt==1:
pname=input("enter product name")
price=float(input("enter price"))
if pname in products:
print("this product exists")
else:
products[pname]=price
elif opt==2:
pname=input("enter product name to update")
price=float(input("enter new price"))
if pname in products:
products[pname]=price
else:
print("product not exists")
elif opt==3:
break
Example:
deptno10_employees={101:50000,102:60000,103:80000}
deptno20_employees={104:70000,105:25000,106:35000}
employee_dict={}
employee_dict.update(deptno10_employees)
employee_dict.update(deptno20_employees)
print(deptno10_employees)
print(deptno20_employees)
print(employee_dict)
2. del d[key]
3. clear()
dict1={1:100,2:200,3:300,4:400}
print(dict1)
del dict1[1]
print(dict1)
del dict1[1]
dict1={1:100,2:200,3:300,4:400}
print(dict1)
dict1.clear()
print(dict1)
String List
**Address Book***
1. Add Address
2. Update Address
3. Delete Address
4. Search Address
5. List Addresses
6. Exit
Case Study
address_book={}
while True:
print("***Address Book***")
print("1. Add Address")
print("2. Update Address")
print("3. Delete Address")
print("4. Search Address")
print("5. List Addresses")
print("6. Exit")
opt=int(input("enter option"))
if opt==1:
name=input("Enter Name")
hno=input("Enter HouseNo")
street=input("Enter Street")
city=input("Enter City")
l=[hno,street,city]
if name in address_book:
print("Address with this name exists")
ans=input("overwrite existing address")
if ans=='yes':
address_book[name]=l
else:
address_book[name]=l
elif opt==2:
name=input("Enter name to update")
if name in address_book:
hno=input("Enter hno")
street=input("Enter street")
city=input("Enter city")
address_book[name]=[hno,street,city]
else:
print("Input name not exists")
elif opt==3:
name=input("Enter name to delete")
if name in address_book:
del address_book[name]
print("Address Deleted")
else:
print("name not exists")
elif opt==4:
name=input("Enter name")
if name in address_book:
l=address_book[name]
print("Hno :",l[0])
print("Street :",l[1])
print("City :",l[2])
else:
print("name not eixsts")
elif opt==5:
for name,l in address_book.items():
print(name,l[0],l[1],l[2])
elif opt==6:
break
Example
dict1={2019:{'jan':10000,'feb':20000},2020:{'jan':30000,'feb':34000}}
print(dict1)
for year,sales in dict1.items():
print(year,sales)
for month,sale in sales.items():
print(month,sale)
Dictionary Comprehension
Example
dict1={1:10,2:20,3:30,4:40,5:50}
dict2={}
# without comprehension
for key,value in dict1.items():
dict2[key]=value
print(dict1)
print(dict2)
# with comprehension
dict3={key:value for key,value in dict1.items()}
print(dict3)
Example
# create dictionary where store key as number value as squre of that
number
# without comprehension
dict1={}
for num in range(1,11):
dict1[num]=num**2
print(dict1)
# with comprehension
Functions
>>> str1="python"
>>> str2="python"
>>> id(str1)
53609440
>>> id(str2)
53609440
>>> str1="R"
>>> id(str1)
14342400
>>> str2[0]="P"
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
str2[0]="P"
TypeError: 'str' object does not support item assignment
>>>
1. Index
2. Slicing
3. For loop
4. Iterator
Using index we can read only one character from string. Index allows to
read in sequential and random order. Like list string can be read using +ve
and –ve index.
Example
str1="PYTHON"
for i in range(len(str1)): # 0 1 2 3 4 5
print(str1[i],end=' ')
print()
for i in range(-len(str1),0): # -6 -5 -4 -3 -2 -1
print(str1[i],end=' ')
print()
for i in range(-1,-(len(str1)+1),-1): # -1 -2 -3 -4 -5 -6
print(str1[i],end=' ')
print()
for i in range(len(str1)-1,-1,-1): # 5 4 3 2 1 0
print(str1[i],end=' ')
string slicing
using slicing we can read a part of string. Slicing is done using slice
operator we required start index, stop index and step. It allows to more than
one character from string.
String-name[start:stop:step]
Default start is 0 and stop is len(string) and step is +1
For –ve step default start is -1 and default stop –len(string)
Example
str1="PYTHON"
str2=str1[::]
print(str1)
print(str2)
str3=str1[::-1]
print(str3)
Example
str1="PROGRAMMING"
str2=str1[:]
str3=str1[::-1]
str4=str1[::2]
str5=str1[::-2]
print(str1)
print(str2)
print(str3)
print(str4)
print(str5)
str6=str1[3:8]
print(str6)
str7=str1[-4:-7:-1]
print(str7)
Example
# write a program to find input string is pal or not
str1=input("enter any string")
str2=str1[::-1]
if str1==str2:
print("pal ")
else:
print("not pal")
str1="PROGRAMMING"
for ch in str1:
print(ch,end='')