Lists
Lists
❖ The following are the common operator structures on list data structure
List traverse:-
The list travels is used to access the list elements one by one.
Example:-
If you want to find out summation of list elements then we can access elements
one by one & add to the summation. It is also used to search an element in a list
List in python:-
A list is a sequence data type in python we have the following sequence data types.
a) List b) Tuple c) String.
a) List:-
A list is a sequence data type which has a group of elements. It is a mutable data
type in python. Mutable means changeable. It is a zero based indexing. It has mixed
data type elements.
We can use following syntax to create a list in python.
List variable= [‘element 1 ‘,’element 2 ’,’element 3 ‘,.......]
Example:-
l =[1,2,3]
l1=[‘abc’,’bbc’,’ccc’]
l2=[‘ece’,’50’,’25.25’]
We can access a list elements by using its index value within sq. bracket [ ].
Example:-
l=[1,2,3] then l [ 0] 1
l[1] 2
l[2] 3
Note:-
We can also –ve indexes in order to access the list elements. If you are using
the indexes we can access the elements from starting to ending. If you are using –ve
indexes we can access the elements from ending to starting.
i.e l [1,2,3] then l [-1] 3
l [-2] 2
l [-3] 1
Sliding operation:-
The sliding operation is used to access elements from index to other index.
Example:-
L [ index 1 : index 2 ] then it will access the element from ‘index 1’ to ‘index2-1’ that
menas it will include index 1 but not index 2.
Example:-
l= [1,2,3,4,5] then l [ 1:4 ] 2,3,4
l [ 0:3 ] 1,2,3
❖ If there is no index 1 in slicing operation then by default it will consider the
starting index ( 0 ) as index 1.
❖ If there is no index 2 in slicing operation then by default it will consider as the
starting index as index 2.
Example:-
l [0: ] 1,2,3,4,5
l [ :4] 1,2,3,4
l [-4:-1] 2,3,4
st
1 = [‘apple’,’banana’,’chemy’]
l [0:2] apple, banana
l [ :2] apple, banana
l [1: ] banana, cherry
l [ :-1] apple, banana,
l [: ] apple, banana, cherry.
l [ ::-1] cherry,banana, apple [it is equal to recerse operation.
append ( )
It is used to append element art the end of existed list. It has only one argument i.e
either element or list. We can use this method by using list name & period sign ( . )
Example:-
mylist=[1,2,3,4]
mylist.append(5)
print(mylist) #[1, 2, 3, 4, 5]
new=[7,8]
mylist.append(new)
print(mylist) #[1, 2, 3, 4, 5, [7, 8]]
Insert method:-
Using insert method we can add an element to the list at any position.
insert ( pos,ele )
Example:- mylist = [1,2,3,4]
mylist. insert ( 1,5 )
print ( mylist ) #[ 1,5,2,3,4]
Extend:-
It is used to add a group of elements to the existed list.
Example:- mylist = [1,2,3,4]
new = [7,8]
mylist. extend ( new )
print ( mylist ) #[ 1,2,3,4,7,8]
remove( ):-
It is used to remove an element from the existed list if there is a duplicate element
then th remove method will delete the first occurrence of duplicate element.
Example:-
mylist = [1,2,3,4,5]
mylist. remove ( 2 )
print ( mylist ) #[ 1,3,4,5]
Example:-
mylist = [1,2,3,4,5]
mylist. remove ( 2 )
Print ( mylist ) #[ 1,3,4,5,2,3,4,2]
del:-
It is also used to delete an element based on index.
Example:-
mylist = [1,2,3,4,5]
mylist. remove ( 2 )
print ( mylist ) #[ 1,2,3,4,5]
pop():-
It is used to delete an element which is at ending position.
Example:-
mylist=[1,2,3,4,5]
mylist.pop()
print(mylist) #[1, 2, 3,4]
we can also delete an element by using index.
mylist=[1,2,3,4]
mylist.pop(3)
print(mylist) #[1, 2, 3]
clear():-
It is used to clear all elements from the list.
Example:-
mylist=[1,2,3,4]
mylist.clear()
print(mylist) #[]
replace:-
We can also replace an element in a list as follows.
Example:-
mylist=[1,2,3,4]
mylist[3]=9
print(mylist) #[1, 2, 3, 9]
count():-
It is used to count the specific element in a list.
Example:-
mylist=[1,2,3,4,5,2,3,4,2]
print(mylist.count(2)) #3
index():-
it is used to know the index of an element in a list.
Example:-
mylist=[1,2,3,4,5]
print(mylist.count(2)) #1
sort():-
it is used to sort the elements either ascending or descending.
Example:-
mylist=[1,2,3,4,5,98,45,32,53,6]
mylist.sort()
print(mylist) #[1, 2, 3, 4, 5, 6, 32, 45, 53, 98]
reverse():-
It is used to reverse the elements in a list.
Example:-
mylist=[1,2,3,4,5,6]
mylist.reverse()
print(mylist) #[6, 5, 4,3, 2, 1]
we can also use the reverse like this as follows:
mylist.sort(reverse=True)
mylist[::-1]
len():-
it is used to find the length of a list.
Example:-
mylist=[1,2,3,4,5,6]
print(len(mylist)) #6
max():-
it is used to find the max elements in a list.
Example:-
mylist=[1,2,3,4,5,6]
print(max(mylist)) #6
min():-
it is used to find the min elements in a list.
Example:-
mylist=[1,2,3,4,5,6]
print(min(mylist)) #1
sum():-
it is used to find the summation of all elements in a list.
Example:-
mylist=[1,2,3,4,5,6]
print(sum(mylist)) #21
More on python list:-
Assigning:-
We can assign a list to the another list by using assignment operator.
Example:-
mylist=[10,20,30,40]
newlist=mylist
print(mylist) #[10,20,30,40]
print(newlist) #[10,20,30,40]
In the above example both mylist and newlist reference the same list if we change
any one of the list the same changes will affect in another list.
Example:-
mylist=[10,20,30,40]
newlist=mylist
mylist[2]=50
print(mylist) #[10, 20, 50, 40]
print(newlist) #[10, 20, 50, 40]
copy() method:-
it is used to copy the entire list ot another list, here the list cannot be affected
even if we have changes in the another list.
Example:-
mylist=[10,20,30,40]
newlist=mylist.copy()
print(mylist) #[10, 20, 30, 40]
print(newlist) #[10, 20, 30, 40]
mylist[2]=50
print(mylist) #[10, 20, 50, 40]
print(newlist) #[10, 20, 50, 40]
list() method:-
The list method is also similar to copy method. It is a constructor to construct a
list.
Example:-
mylist=[10,20,30,40]
newlist=list(mylist)
print(mylist) #[10, 20, 30, 40]
print(newlist) #[10, 20, 30, 40]
mylist[2]=50
print(mylist) #[10, 20, 50, 40]
print(newlist) #[10, 20, 30, 40]
all()
any()
The all method written Ture if the all elements evaluates ture. The any method
returns Ture if the any one of ateh elements evaluates ture otherwise False.
Example:-
val1=[1,2,3,4,0]
print(all(val1)) #False
print(any(val1)) #True
val2=[None,None,None,False]
print(all(val2)) #False
print(any(val2)) #False
enumerate()
It is used to add a counter to the iterable and returns it.
Example:-
branch=['ECE','CSE','EEE']
print("return type:",type(branch))
obj=enumerate(branch)
print("return type:",type(obj))
for br in enumerate(branch):
print(br)
for index,val in enumerate(branch):
print("the",index,"element is:",val)
for index,val in enumerate(branch,100):
print(index,val)
"""
output:
return type: <class 'list'>
return type: <class 'enumerate'>
(0, 'ECE')
(1, 'CSE')
(2, 'EEE')
the 0 element is: ECE
the 1 element is: CSE
the 2 element is: EEE
100 ECE
101 CSE
102 EEE
""
ord() method:-
It is used to convert a character into equivalentunicode(ASCII value).
Example:-
name="AITS"
mylist=[]
for i in name:
mylist.append(ord(i))
print(mylist) #[65, 73, 84, 83]
chr():-
It is used to convert the ASCII code into character.
Example-
mylist=[]
for i in range(65,70):
mylist.append(chr(i))
print(mylist) #['A', 'B', 'C', 'D', 'E']
note:-
we can also create an empty list by using square bracket.
Example:- mylist[]
We can also create list using list constructor.
fruits=list(('apple','banana','cherry'))
print(fruits) #['apple', 'banana', 'cherry']
Nested list:-
A list inside another list is called nested list.
Example:- grades=[[80,85,90],[75,82,94],[83,95,76]]
The above example wh have three lists embeddedin singlelist. We can retrew or
access individual list from the nested list as follows.
grades[0] [80,85,90]
grades[1] [75,82,94]
grades[2] [83,95,76]
we can also return the individual elements from the list as follows.
grades[0][0] 80
grades[0][1] 85
grades[0][2] 90
grades[1][0] 75
grades[1][1] 82
grades[1][2] 94
grades[2][0] 83
grades[2][1] 95
grades[2][2] 76
we can calculate each exam avg as follows.
grades=[[80,85,90],[75,82,94],[83,95,76]]
sum=0
k=0
while(k<len(grades)):
sum=sum+grades[k][0]
k=k+1
e1avg=float(sum/len(grades))
print('sum of exam1 is:',sum)
print('avg of exam1 is:',e1avg)
"""
output:
sum of exam1 is: 238
avg of exam1 is: 79.33333333333333
"""
We can also calculate the class avg of each student and copied those avg into
empty list.
grades=[[80,85,90],[75,82,94],[83,95,76]]
sum=0
k=0
clsavg=[]
while(k<len(grades)):
avg=flaot((grades[k][0]+grades[k][1]+
grades[k][2]/len(grades[k]))
clsavg.append(avg)
k=k+1
print('class average is:',clsavg)
Iterationg over the list:-
We can iterate the list by using iterative statements those are for and while. We
can iterate the list based on sequence element and as well as indexes
Example:-
num=[1,2,3,4,5]
sum=0
for x in num: #the beside is used to find the summation based on sequence
sum+=x elements.
print('sum is:',sum)
"""
output:
sum is: 15
"""
num=[1,2,3,4,5]
sum=0
for x in range(0,5):
sum=sum+num[x]
print('sum is:',sum)
"""
output:
sum is: 15
"""
#The beside example is used to find the summation based on the index values. Here
the indices are getting from built_in range function. The range function generates the
sequence numbers from starting index to ending index-1.
Using while loop;-
We can also iterate the list by using while loop. Generally it is used to search an
element in a list.
Example:-
nums=[1,2,3,4,5]
item=4
flag=False
k=0
while(k<len(nums)and not flag):
if(nums[k]==item):
flag=True
else:
flag=False
if(flag==True):
print('item found')
else:
print('item not found')
List comprehension:-
List comprehension is a elegant way to define and create a list. It generates a
varied sequences. It is a powerful feature of lists.
It has the following syntax.
[<expression> for<expression> in<iterable> <condition>]
#write a python program to display squares of numbers from 1 to 10.
for x in range(1,11):
print('squares:',x**2)
print([x**2 for x in range(1,11)])
"""
output:
squares: 1
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares: 4
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares: 9
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares: 16
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares: 25
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares: 36
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares: 49
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares: 64
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares: 81
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares: 100
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
"""
#write a python program to find the cubes of numbers from 1 to 20.
cubes=[x**3 for x in range(1,11)]
print(cubes)
"""
output:
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
"""
#write a python program to find the odd numbers from 1 to 10 using list
comprehension.
odd=[x for x in range(1,11) if x%2!=0]
print(odd)
"""
output:
[1, 3, 5, 7, 9]
"""
#write a python program to find the even numbers from 1 to 20 using list
comprehension.
even=[x for x in range(1,21) if x%2==0]
print(even)
"""
output:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
"""
#write a python program to extract only positive numbers from the given string.
nums=[-1,1,-2,2,-3,3,-4,4]
pos=[x for x in nums if x>0]
print(pos) #[1, 2, 3, 4]
#write a python program to extract only vowels from the given string.
name="welcome to ABCD company"
vow=[v for v in name if v in 'aeiou']
print(vow) #['e', 'o', 'e', 'o', 'o', 'a']
"""
#write a python program to find summation of cubes of numbers from 1 to 20.
cubes=[sum([x**3 for x in range(1,21)])]
print(cubes) #[44100]
#write a python program to list ascii values of given string.
ch='AITS'
asc=[ord(ch)for ch in 'AITS']
#write a python program to find the temp values which are >=100.
temp=[80,85,96,100,102,96,105]
print([t for t in temp if t>=100]) #[100, 102, 105]
"""
#write a python program to convert temp int0o celsius which are<100.
temp=[80,96,100,102,96,105]
print([(t-32)*5/9 for t in temp if t<100])
#[26.666666666666668, 35.55555555555556, 35.55555555555556]
#write a python program to replace consonants with stars(*) in a given string.
AITS
print[x if x in 'aeiou' else '*' for x in 'AITS']
#write a python program to display prime numbers from 1 to 20.
print([p for p in range(1,21) if all(p%y!=0 for y in range(2,p))])
""""[1, 2, 3, 5, 7, 11, 13, 17, 19]"""
#write a python program to extract integers float and strings from the mixed
type list.
mylist=[2,5.3,'ECE',2.8,4,6,'CSE']
print([x for x in mylist if type(x)==int])
print([x for x in mylist if type(x)==float])
print([x for x in mylist if type(x)==str])
"""
output:
[2, 4, 6]
[5.3, 2.8]
['ECE', 'CSE']
"""
Concatination or Merging:-
We can use +operator to concatenate two different list.
Example:-
list1=['a','b','c']
list2=[1,2,3]
list3=list1+list2
print(list3) #['a', 'b', 'c', 1, 2, 3]
Repeatetions:-
We can repeat the same lists by using star(*) operator.
Example:-
list1=['a','b']
print(list1*3) #['a', 'b', 'a', 'b', 'a', 'b']
cmp() method:-
it is used to compare the list. It will return “one” if the first list is greater than
second list. It will return “-1”. If the first is smaller than second list. It will return “0”.
If the both the lists are having same elements.
Example:-
l1=[1,2,4,5]
l2=[1,2,5,8]
l3=[1,2,5,8,10]
l4=[1,2,4,5]
print(cmp(l1,l2))
print(cmp(l2,l3))
print(cmp(l1,l4))
note:-
Whenever we are using cmp() method then we have to use same type of input.
cmp(list1,list2)
Tuple:-
A tuple is an immutable linear data structure, we cannot altered furtherly because
it is not changeable and it is similar to list type. It is also ordered and indexed mixed
data type. Here the duplicate elements are allowed. We can create a tuple by enclosing
the elements within open brackets.
Example:-
#t=(10,20,30)
#mytuple=(1,’AITS’,20.2)
We can use type method in order to know the type of a variable.
Example:-
t=(10,20,30)
print(type(t)) #<class 'tuple'>
We can also access the tuple elements based on its index values.
Example:-
t=(10,20,30)
print(type(t)) #<class 'tuple'>
print(t[0],t[1],t[2]) #10 20 30
we can also perform the slicing operation on tuple.
Example:-
t=(10,20,30)
print(t[0:2])
print(t[ :1])
print(t[1: ])
print(t[ :-1])
print(t[: :-1])
"""
output:
(10, 20)
(10,)
(20, 30)
(10, 20)
(30, 20, 10)
"""
We can also concatenate two tuples by using + operator
Example:-
t=(10,20,30)
mytuple=(1,'AITS',20.2)
t1=t+mytuple
print(t1) #(10, 20, 30, 1, 'AITS', 20.2)
we can find out the length of a tuple by using length function or length method.
Example:-
t1=(10, 20, 30, 1, 'AITS', 20.2)
print(len(t1)) #6
we can also find out the max and min element in tuple by using max() and min().
Example:-
t1=(10, 20, 30, 1, 'AITS', 20.2)
print(max(t1)) #AITS
print(min(t1)) #1
We can also find summation of tuple element using sum().
Example:-
t=(10,20,30)
print(sum(t)) #60
we can also apply all() and any() on tuple, the all() returns “True”, if all elements
evaluates True, any() returns “True” if any elements evaluates True.
t=(1,2,3,0)
print(all(t)) #True
print(any(t)) #False
we can also apply enumerate () on tuple, enumerate() adds a counter to the iterate
and returns it.
t=(10,20,'AITS','dilip',20.2)
for x in enumerate(t):
print(x)
"""
output:
(0, 10)
(1, 20)
(2, 'AITS')
(3, 'dilip')
(4, 20.2)
"""
t=(10,20,'AITS','dilip',20.2)
for x,y in enumerate(t,11):
print(x,y)
"""
output:
11 10
12 20
13 AITS
14 dilip
15 20.2
"""
We cannot insert, append, del a tuple element because a tuple is an immutable(not
changeable).
If we apply del and tuple then it simply deletes the entire tuple from the memory.
Example:-
del t
print(t) #error message t is not defined.
We can create a tuple by using tuple(). It can also use to convert any sequence
type to tuple type.
Example:-
name=tuple(‘aits’)
print(name) #(‘a’,’i’,’t’,’s’)
we can also create a nested tuple.
t1=(10, 20, 30, 1, 'AITS', 20.2)
t2=(40,0,'SUNNY','dilip',20.5)
t=(t1,t2)
print(t)
print(t[0])
print(t[1])
print(t[0][0])
"""
output:
((10, 20, 30, 1, 'AITS', 20.2), (40, 0, 'SUNNY', 'dilip', 20.5))
(10, 20, 30, 1, 'AITS', 20.2)
(40, 0, 'SUNNY', 'dilip', 20.5)
10
"""
If you want to create a tuple which has single element then we can do as follows.
newTuple=(1,3,4)
print(newTuple) #(l,2,3)
print(type(newTuple)) #<class 'tuple'>
If you want to create a tuple which has single element then you have to do as follows.
Example:-
newTuple=(1)
print(newTuple) #1
print(type(newTuple)) #<class 'tuple'>
The above example the python will treat the new tuple as integer type.
We can also sort the elements of tuple by using sorted()
t=(1,2,3,5,4,6)
print(sorted(t)) #[1, 2, 3, 4, 5, 6]
print(sorted(t,reverse=True)) #[6, 5, 4, 3, 2, 1]
Dictionaries and Sets:-
A dictionary is a mutable associative data structure of variable length. It is
unordered. It has key_value paired. We can access the values or elements based on
that key only. We cannot use index values here. Always the keys are unique. There is no
duplicate keys. But we may have duplicate values. The key may be string, number or a
tuple. The list cannot act as key.
❖ We can create a dictionary in a python by enclosing key_value pair within curly
braces.
dict_name={‘key’:’value’}
❖ In dictionary key and values are separated by colon symbol. Key_value pair is
also called as an item.
Example:-
mydict={
'college':'AITS',
'branch':'CSE',
'count':63
}
print(mydict)
#{'college': 'AITS', 'branch': 'CSE', 'count': 63}
❖ We can also create an empty dictionary as follows.
d={}
❖ In mydict dictionary the keys are college, branch, count and values are AITS,
CSE, 63.
len():-
we can find the length of dictionary by using len().
Example:-
mydict={
'college':'AITS',
'branch':'CSE',
'count':63
}
print(len(mydict))
Accessing:-
we can access the dictionary values based on their keys.
Example:-
mydict={
'college':'AITS',
'branch':'CSE',
'count':63
}
print(mydict['college']) #AITS
print(mydict['branch']) #CSE
print(mydict['count']) #63
get():-
we can also use get method to access dictionary values based on keys.
Example:-
mydict={
'college':'AITS',
'branch':'CSE',
'count':63
}
print(mydict.get[‘college’]) #college
set() default():-
It is used to set a default value to the key, if the key is not existed otherwise it
returns the existed value of the key.
Example:-
mydict={
'college':'AITS',
'branch':'CSE',
'count':63
}
x=mydict.setdefault(‘college’,’KVSR’)
print(x) #AITS
#if there is no ‘course’ key then
y=mydict.setdefault(‘course’,’B.Tech’)
print(x)
Adding:-
We can add an item to the existed dictionary as follows.
mydict={
'college':'AITS',
'branch':'CSE',
'count':63
}
mydict('new branch')='ece'
print(mydict)
#{‘colllege’:’AITS’,’branch’:’CSE’,’count’:63,’newbranch’:’cse’}
the above statement if the key is not there. Then simply it add an item to the
dictionary if the key is existed then it will perform the update.
Example:-
mydict(‘count’)=63
print(mydict) # {‘college’:’AITS’,’branch’:’ECE’,
‘count’:’63’}
Update ( ):-
The update method is used to update the dictionary items, if the items are already
existed simply it replace if the items are not existed simply it will add.
Example:-
d={1:’ECE’,2:’CSE’}
d.update ({2:’EEE’})
print(d) #{1:’ECE’,2:’EEE’}
d.update ({3:’civil})
print(d) #{1:’ECE’,2:’EEE’,3:’civil’}
❖ We can also add a list to the dictionary as follows
l=[[a,1], [b,2]]
d.update ( dict(l))
print(d) #{1:’ECE’,2:’CSE’,’a’:1,’b’:2}
Removing:-
We can remove the dictionary item in different ways.
a) del ( )
The del is used to delete a particular item based on key.
Example:-
del mydict [‘count’]
b) pop ( )
A pop ( ) is also used to delete an item from the dictionary it will also return the
deleted value
Example:-
d= {1:’ECE’,2:’CSE’,3:’EEE’}
x= d,pop (2)
print ( x,’was deleted’,’and dictionary is’,d)
# {1:’ECE’,3:’EEE’}
c) pop item ( )
It is used to delete an arbitrary item from the dictionary.
Example:-
d= {1:’ECE’,2:’CSE’,3:’EEE’}
x= d,popitem ( )
print ( x,’was deleted’,’and dictionary is’,d)
# {1:’ECE’,2:’CSE’}
❖ Popitem( ) is deleted from end onwards.
d) clear ( )
It is used to empty the dictionary.
d= {1:’ECE’,2:’CSE’,3:’EEE’}
d.clear( )
print (d) #{ }
Note:-
d= {1:’ECE’,2:’CSE’,3:’EEE’}
del d
print(d) #error message
keys ( ):-
It is used to extract list of values from the dictionary.
Example:-
d={1:’ECE’,2:’CSE’}
for x in d.keys( ):
print(x) #1
2
values ( ):-
It is used to extract the list of keys from the dictionary.
Example:-
d={1:’ECE’,2:’CSE’}
for x in d.values( ):
print(x) # ECE
CSE
items( ):-
It is used to extract key & values pair from the dictionary =.
Example:-
d={1:’ECE’,2:’CSE’}
for x in d.items( ):
print(x) #(,’ECE’)
(,’CSE’)
fromkeys( ):-
It is used to create a dictionary from the group which has group of keys and
assigned same value to the each key.
Example:-
1) d={ }
x=(1,2,3)
y=(‘ECE’)
d.fromkeys (x,y)
print(d) #{:’ECE’,2:’ECE’,3:’ECE’}
2) d= { }
x=(1,2,3)
d.fromkeys (x)
print(d) #{1:None 2:None 3:None}
copy ( ):-
it is used to copy one dictionary
Example:-
d={1:’ECE’,2:’CSE’}
d1=d.copy ( )
print(d1)
Set data type:-
Set:-
It is a mutable data type. It is unordered and it will not allow duplicate
elements. We can create a set by enclosing the elements within curly braces { }. The
elements may be different type. (mixed data values). If you have a duplicate elements
in a set simply it will remove the duplicate & display original set.
Example:-
s= {1,2,3,’ECE’,20.5}
print(s) #{1,2,3,,’ECE’,20.5}
we can create an empty set by using set constructor. Generally the sets are
represented in curly braces. We don’t use curly braces we can create an empty set.
Example:-
set={ }
print(type(s)) #<class ‘dict’>
s1=set( )
print(type(s1)) #<class ‘set’>
add( ):-
It is used to add a single element to the set. It has only one parameter i.e value.
Example:-
myset = {1,2,3,4,5,6,4,3,2}
print (myset) #{1,2,3,4,5,6}
myset.add(8)
print (‘After adding :’,myset) # {1,2,3,4,5,6,7,8}
update( ):-
It is used to add multiple elements to the set. Generally it will accept list, tuple,
string or other set of values.
Example:-
myset= {1,2,3,4,5,6,4,3,2}
myset. update([7,9,10])
print (myset) #{1,2,3,4,5,6,7,9,10}
remove( ):-
It is used to remove a particular element from the set.
Example:-
myset = {1,2,3,4,5,6,79,10}
myset.remove(2)
print(myset) #{1,3,4,5,6,7,8,9}
discard( ):-
It is also used to remove an element from the set. A difference between remove
& discard is a discard will not generate any error even an element is not existed. But
the remove method will rise error message if the element is not existed.
myset = {1,2,3,4,5,6,7,8,9}
myset.remove(2)
print (myset) #{1,2,3,4,5,6,7,8,9}
myset.discard(5)
print (myset) #{1,3,4,6,7,8,9}
myset.discard(2)
myset.remove(5) #error message
print( myset)
pop( ):-
A pop method will delete an element randomly because set is unordered. It can
also return a deleted element.
myset = {1,2,3,4,5,6,7,8,9}
print (‘ the pop elements is:’,myset,pop()) # delete ray no. because set is
unordered
print(myset) #{2,3,4,5,6,7,8,9}
clear( ):-
It is used to clear the all elements from the set.
Example:-
myset = {1,2,3,4,5,6,7,8,9}
myset.clear( )
print (myset) #set( )
Set operations:-
We can apply set operation on set those are union, intersection, difference,
symmetric_ difference( )
s1={1,2,3,’ECE’,’CSE’,2.5}
s2={1,2,4,5,’cse’}
s1/s2
or #{1,2,3,4,5’,ECE’,’cse’,2.5}
s1.union(s2)
Union:-
It is used to perform the union operation on two different sets. It returns a new
set from the existed set in python the union can be represented as ‘|’ we can also use
an inbuilt function union( )
s1={1,2,3,’ECE’,’CSE’,2.5}
s2={1,2,4,5,’cse’}
print(‘After union :’,s1|s2)
print(‘After union :’,s1.union (s2))
#{1,2,3,4,5’,ECE’,’cse’,2.5}
Intersection:-
The intersection of s1 & s2 is a set of elements that are common in both the sets,
it can be perform using and( & ) operator or using intersection ( ).
s1={1,2,3,’ECE’,’CSE’,2.5}
s2={1,2,4,5,’cse’}
print(‘After intersection :’,s1 & s2)
print(‘After intersection :’,s1.intersection (s2)
# {1,2,’cse’}
difference( ):-
The difference of s1 & s2 is a set of elements that are only in s1 not in s2. It can
be perform using “-” operator or a difference ( ).
print(‘After difference :’,s1 - s2)
print(‘After difference :’,s1. difference (s2))
# {3,’ECE’,2.5}
Symmetric_difference( ):-
A symmetric- difference of s1 & s2 is a set of elements in both s1 & s2 except that
are common in both the set.
It can be perform by using “ ^ “ symbol or by using symmetric_difference ( )
print(‘After symmetric _difference :’,s1 ^ s2)
print(‘After symmetric_difference :’,s1. symmetric_difference (s2))
#{3,4,5,’ECE’,2.5}
More function on sets:_
1) intersection_update( ):-
It is used to perform the intersection & simply it update same result to
the called set or invoked set.
s1={1,2,3,’ECE’,’CSE’,2.5}
s2={1,2,4,5,’cse’}
s1. intersection (s2) # {1,2,’cse’}
2) difference_update( ):-
It will perform symmetric_difference operation & update result to the
invoked set.
Isdisjoint( )
It return True if the sets are not having common elements.
s1={1,2,3,4,5}
s2={1,2,3}
print (s1. isdisjoint (s2)) #False.
Issuperset( )
It returns True if the set is superset of another set otherwise False.
print (s1. issuperset (s2)) #True.
Note:-
Always the set elements are immutable elements.
Functions:-
Program routines:-
Poutine is a named group of instructions that are used to perform a task we can
call a routine as many times as needed.
formal parameters
return (a+b)
print(‘the result is :’, add (10,20))
actual arguments
#Write a python program to find whether the person is elder (or) younger
(or) twins using functions.
def ordered(n1,n2):
return n1<n2
n1=int(input('enter your age:'))
n2=int(input('enter your brother/sister age:'))
if(ordered(n1,n2)):
print('He/She is elder brother/sister')
elif(ordered(n1,n2)):
print('He/She is younger brother/sister')
else:
print('they are twins')
"""
output:
enter your age:18
enter your brother/sister age:16
they are twins
"""
The correspondence of actual arguments and formal parameters is determined
based on order of passed arguments not by their names.
Types of arguments:-
In python, we have the following types of arguments.
a) immutable arguments
b) mutable arguments
c) positional arguments
d) keyword arguments
e) default arguments
f) variable_ length arguments
immutable arguments:-
The arguments which are not changed after completion of function definition
these arguments are called immutable arguments.
def countdown():
while(n>=0):
if(n!=0):
print(n,end='')
else:
print(n)
n=n-1
num=10
countdown(num)
print('the number is:',num)
Where number is a immutable arguments because it remains same.
Mutable argument:-
The arguments which are modified after completion of function definition are
called mutable arguments.
def findsum(nums):
sum=0
for x in range(len(nums)):
if(nums[x]<0):
nums[x]=0
else:
sum+=nums[x]
nums=[-1,2,3,-4,5]
print('the list is:',nums)
findsum(nums)
print('after definition,the list is:',nums)
"""
output:
the list is: [-1, 2, 3, -4, 5]
after definition,the list is: [0, 2, 3, 0, 5]
"""
Where nums is a mutable arguments because before calling. The list numbers is remains
same but after calling, in function definition simply we are replacing negatives with
zeroes the same changes are reflected in original list. So that the list gets modified
that’s why we are calling it as mutable arguments. Where sets, dictionaries, list are
mutable arguments where as tuple is a immutable arguments.
Positional arguments:-
The positional arguments, which are assigned to a particular parameter based on
its position are called positional arguments.
Example:-
Example:-
def display(fname,lname):
print(fname,'',lname)
fname=input('enter first name:')
lname=input('enter last name:')
display(fname,lname)
display(lname,fname)
"""
output:
enter first name:dilip
enter last name:byella
dilip byella
byella dilip
"""
Keyword arguments:-
This is an arguments that is specified by the parameter name.
#Write a python program to demonstrates the working of keyword argument
def addup(first,last):
if(first>last):
sum=-1
else:
sum=0
for x in range(first,last+1):
sum+=x
return sum
print('the result is:',addup(first=1,last=10))
"""
output:
the result is: 55
"""
default argument:-
Default arguments is an arguments that can be optionally provided.
Example:-
def yearterm(amount,interest,term=2):
yearterm(35,000,25)
#write a python program to demonstrates the working of default argument.
def addup(first,last):
if(first>last):
sum=-1
else:
sum=0
for x in range(first,last+1):
sum+=x
return sum
print('the result is:',addup(first=1,last=10))
print('the result is:',addup(first=1,last=10,incr=1))
print('the result is:',addup(10,20,2))
where incr is adefault argument.
Another example for default
def display(country='india'):
print('country name:',country)
display()
display('Australia')
display('America')
"""
output:
country name: india
country name: Australia
country name: America
"""
Variable length argument:-
The variable length arguments are used whenever we don’t know the how many
argument that will passed to our functions. We have the following 2 variable argument
1) Arbitrary argument (,*arg)
2) arbitrary keyword argument ( **kwarg)
Arbitrary argument:-
It will we whenever we don’t know the how many arguments that will pass in a
function. it will receive in the form of tuple & we can access them using index.
Example:-
def display(*name):
print('First name:',name[0])
print('last name:',name[1])
fname=input('enter first name:')
lname=input('enter last name:')
display(fname,lname)
"""
output:
enter first name:raavan
enter last name:sunny
First name: raavan
last name: sunny
"""
Arbitrary keyword argument:-
It will use whenever we don’t know how many keyword argument that will function
to a pass it will receive argument in the form dictionary. We can access them by using
keyword.
Example:-
def display(**name):
print('First name:',name['fname'])
print('last name:',name['lname'])
return name
first=input('enter first name:')
last=input('enter last name:')
print(display(fname=first,lname=last))
"""
output:
enter first name:dilip
enter last name:byella
First name: dilip
last name: byella
{'fname': 'dilip', 'lname': 'byella'}
"""
Variable scope:-
The scope will define a life time of a variable. We have the following two variable
scopes.
a) Local scope
b) Global scope
Local scope and Local variable:-
The variable which defines inside a function is called local variable & it has a local
scope it can access only within a function where we have created.
Example:-
def func1():
n=10
print('n value is:',n)
def func2():
n=20
print('n value is:',n)
func(c)
print('n value is:',n)
func1()
func2()
❖ if you remove n variable from funnel we will get an error mes. Lite n is not
defined.
Global scope & global variable:-
The variable which is defined outside of the function is called global variable.
It has only global scope it can access by any function & access any where in the
program.
Example:-
n=10
def func1():
print('n value is:',n)
def func2():
print('n value is:',n)
func1()
print('n value is:',n)
func1()
func2()
"""
output:
n value is: 10
n value is: 10
n value is: 10
n value is: 10
"""
Recursive function:-
The function calling itself is called recursive function. The technic is
known as recursion. It is more efficient when we right proper logic otherwise it will
waste the memory space & some time it will enter into infinite state.
Syntax:-
Example:-
#Write a python program to find the summation of n natural numbers using
recursive function.
def recsum(n):
if(n!=0):
return n+recsum(n-1)
else:
return 0
n=int(input('enter n value:'))
print('the sum is:',recsum(n))
"""
output:
enter n value:8
the sum is: 36”””
1)write a python program to find the factorial of number using recursion.
def refact(n):
if(n!=0):
return n*refact(n-1)
else:
return 1
n=int(input('enter n value:'))
print('the factorial is:',refact(n))
"""
output:
enter n value:5
the factorial is: 120
"""
2)write a python program to find n Fibonacci series using recursive function.
def recfib(n):
if(n==0):
return 0
elif(n==1):
return 1
else:
return(recfib(n-1)+recfib(n-2))
n=int(input('enter n vlaue:'))
print('the fibonacci numbers are:')
for x in range(0,n):
print(recfib(x))
"""
output:
enter n vlaue:5
the fibonacci numbers are:
0
1
1
2
3
"""
PROGRAMS ON LIST & TUPLE TYPE:
#WRITE A PYTHON PROGRAM TO DEMONSTRATE WORKING OF LIST IN
PYTON AND IT'S OPERATIONS
mylist=[1,2,3,4]
new=[10,11]
newlist=[15,12,13,12]
#length
print('length of mylist is:',len(mylist))
#accessing
print('The first element is:',mylist[0])
print('The second element is:',mylist[1])
print('The third element is:',mylist[2])
print('The fourth element is:',mylist[3])
#slicing
print('mylist[0:3]',mylist[0:3])
print('mylist[:2]',mylist[:2])
print('mylist[1:]',mylist[1:])
print('mylist[-3:-1]',mylist[-3:-1])
print('mylist[::-1]',mylist[::-1])
#append
mylist.append(5)
print('After append,the list is:',mylist)
#insert
mylist.insert(1,6)
print('After insert,the list is:',mylist)
mylist.append(new)
print('After append,the list is:',mylist)
#extend
mylist.extend(newlist)
print('After extend,the list is:',mylist)
#accessing
print('The sixth element is:',mylist[6])
print('The seventh element is:',mylist[7])
print('The eight element is:',mylist[8])
print('The sixth of zero index element is:',mylist[6][0])
#remove
newlist.remove(12)
print('after remove ,the list is:',newlist)
#del
del newlist[2]
print('after delete ,the list is:',newlist)
#pop
print('before pop() ,the list is:',mylist)
mylist.pop()
print('after pop() ,the list is:',mylist)
print('before pop(6) ,the list is:',mylist)
mylist.pop(6)
print('after pop(6) ,the list is:',mylist)
#clear
print('before clear() ,the list is:',new)
new.clear()
print('after clear() ,the list is:',new)
#count
l1=[1,2,2,3,3,4,2]
print('count(2) is:',l1.count(2))
#index
print('index(2) is:',l1.index(2))
#sort
mylist.sort()
print('Sorting is:',mylist)
mylist.sort(reverse=True)
print('Sorting is:',mylist)
#reverse
mylist.reverse()
print('Reverse list is:',mylist)
#copy and assigning
l1=[1,2,3]
l2=l1
print(l1,l2)
l1[0]=4
print(l1,l2)
l2=l1.copy()
print(l1,l2)
l1[0]=5
print(l1,l2)
l2=list(l1)
print(l1,l2)
l1[0]=6
print(l1,l2)
#max,min & sum
print('Max of mylist is:',max(mylist))
print('Min of mylist is:',min(mylist))
print('sum of mylist is:',sum(mylist))
#all,any
val1=[1,2,3,4,0]
print('all:',all(val1))
print('any:',any(val1))
val2=[1,2,3,4,5]
print('all:',all(val2))
print('any:',any(val2))
val3=[None,None,None,False]
print('all:',all(val3))
print('any:',any(val3))
#enumerate
branch=['ece','eee','cse']
obj=enumerate(branch)
print('Return Type:',type(obj))
for (i,j) in enumerate(branch):
print('The',i,'element is:',j)
#ord,chr
name='AITS'
n=[]
m=[]
for i in name:
n.append(ord(i))
for j in n:
m.append(chr(j))
print(n,m)
#comparison
l1=[1,2,4,5]
l2=[1,2,5,8]
l3=[1,2,5,8,10]
l4=[1,2,4,5]
print(l2>l1)
print(l2<l3)
print(l1==l4)
'''
OUTPUT
length of mylist is: 4
The first element is: 1
The second element is: 2
The third element is: 3
The fourth element is: 4
mylist[0:3] [1, 2, 3]
mylist[:2] [1, 2]
mylist[1:] [2, 3, 4]
mylist[-3:-1] [2, 3]
mylist[::-1] [4, 3, 2, 1]
After append,the list is: [1, 2, 3, 4, 5]
After insert,the list is: [1, 6, 2, 3, 4, 5]
After append,the list is: [1, 6, 2, 3, 4, 5, [10, 11]]
After extend,the list is: [1, 6, 2, 3, 4, 5, [10, 11], 15, 12, 13, 12]
The sixth element is: [10, 11]
The seventh element is: 15
The eight element is: 12
The sixth of zero index element is: 10
after remove ,the list is: [15, 13, 12]
after delete ,the list is: [15, 13]
before pop() ,the list is: [1, 6, 2, 3, 4, 5, [10, 11], 15, 12, 13, 12]
after pop() ,the list is: [1, 6, 2, 3, 4, 5, [10, 11], 15, 12, 13]
before pop(6) ,the list is: [1, 6, 2, 3, 4, 5, [10, 11], 15, 12, 13]
after pop(6) ,the list is: [1, 6, 2, 3, 4, 5, 15, 12, 13]
before clear() ,the list is: [10, 11]
after clear() ,the list is: []
count(2) is: 3
index(2) is: 1
Sorting is: [1, 2, 3, 4, 5, 6, 12, 13, 15]
Sorting is: [15, 13, 12, 6, 5, 4, 3, 2, 1]
Reverse list is: [1, 2, 3, 4, 5, 6, 12, 13, 15]
[1, 2, 3] [1, 2, 3]
[4, 2, 3] [4, 2, 3]
[4, 2, 3] [4, 2, 3]
[5, 2, 3] [4, 2, 3]
[5, 2, 3] [5, 2, 3]
[6, 2, 3] [5, 2, 3]
Max of mylist is: 15
Min of mylist is: 1
sum of mylist is: 61
all: False
any: True
all: True
any: True
all: False
any: False
Return Type: <class 'enumerate'>
The 0 element is: ece
The 1 element is: eee
The 2 element is: cse
[65, 73, 84, 83] ['A', 'I', 'T', 'S']
True
True
True
'''
#write a python program to read elements into a list and display them and also
find maximum element in a list
mylist=[]
size=int(input('Enter list size:'))
for x in range(size):
ele=int(input('Enter your element:'))
mylist.append(ele)
print('The list elements are:')
for e in range(len(mylist)):
print(mylist[e],end=' ')
print()
max=min=mylist[0]
sum=0
for e in range(len(mylist)):
if(max<=mylist[e]):
max=mylist[e]
if(min>=mylist[e]):
min=mylist[e]
sum+=mylist[e]
print('The maximum element is:',max)
print('The minimum element is:',min)
print('The summation of all elements is:',sum)
'''
OUTPUT
Enter list size:5
Enter your element:20
Enter your element:10
Enter your element:60
Enter your element:50
Enter your element:40
The list elements are:
20 10 60 50 40
The maximum element is: 60
The minimum element is: 10
The summation of all elements is: 180
'''
if not lfound:
pout+=ch
if encrypt:
print('Your Encrypted password is:',pout)
else:
print('Your Decrypted password is:',pout)
'''
OUTPUT:
Enter (e) to encrypt and (d) to decrypt:e
Enter Your password:nagendra
Your Encrypted password is: gntrgqkn
Enter (e) to encrypt and (d) to decrypt:d
Enter Your password:gntrgqkn
Your Decrypted password is: nagendra
'''
#values()
for x in mydict.values():
print(x)
#items()
for x in mydict.items():
print(x)
#copy()
new=mydict.copy()
print(new)
'''
OUTPUT:
My Dictionary is: {'college': 'AITS', 'branch': 'ECE', 'count': 65}
Length of dictionary is: 3
First Element: AITS
Second Element: ECE
Third Element: 65
First Element using get(): AITS
After adding: {'college': 'AITS', 'branch': 'ECE', 'count': 60, 'course': 'B.Tech'}
{'college': 'AITS', 'branch': 'cse', 'count': 63, 'course': 'B.Tech'}
{'college': 'AITS', 'branch': 'cse', 'count': 63, 'course': 'B.Tech', 'name': 'nag', 'num':
1241}
{'college': 'AITS', 'branch': 'cse', 'count': 63, 'course': 'B.Tech', 'name': 'nag', 'num':
1241, 'a': 1,
'b': 2}
{'college': 'AITS', 'branch': 'cse', 'course': 'B.Tech', 'name': 'nag', 'num': 1241, 'a': 1,
'b': 2}
B.Tech was deleted. {'college': 'AITS', 'branch': 'cse', 'name': 'nag', 'num': 1241, 'a':
1, 'b': 2}
('b', 2) was deleted. {'college': 'AITS', 'branch': 'cse', 'name': 'nag', 'num': 1241, 'a':
1}
{'college': 'AITS', 'branch': 'cse', 'name': 'nag', 'num': 1241, 'a': 1}
AITS
{'college': 'AITS', 'branch': 'cse', 'name': 'nag', 'num': 1241, 'a': 1}
{1: ('ece', 'cse', 'eee'), 2: ('ece', 'cse', 'eee'), 3: ('ece', 'cse', 'eee')}
college
branch
name
num
a
AITS
cse
nag
1241
1
('college', 'AITS')
('branch', 'cse')
('name', 'nag')
('num', 1241)
('a', 1)
{'college': 'AITS', 'branch': 'cse', 'name': 'nag', 'num': 1241, 'a': 1}
'''
#write a python program to display temperature in a day using dictionary
temp={'sun':68,'mon':73,'tue':75,'wed':82,'thr':86,'fri':94,'sat':97}
daynames={'sun':'sunday','mon':'monday','tue':'tuesday','wed':'wedneday',
'thr':'thursday','fri':'friday','sat':'saturday'}
day=input("Enter 'sun','mon','tue','wed','thr','fri','sat':")
print('The average Temprature of ',daynames[day],'is',temp[day],'degrees')
'''
OUTPUT:
Enter 'sun','mon','tue','wed','thr','fri','sat':wed
The average Temprature of wedneday is 82 degrees
'''
#WRITE A PYTHON PROGRAM TO DEMONTARTE THE WORKING OF VARIOUS
OPERATIONS ON SET
s={}
print(type(s))
s=set()
print(type(s))
s1={1,2,3,4,5,6,4,3,2}
print('myset is:',s1)
#len()
print('My set length is:',len(s1))
#copy()
s3=s1.copy()
print('After copy:',s3)
#add()
s1.add(8)
print('After add:',s1)
#update()
s1.update(['ece','cse'])
print('After Update:',s1)
#remove()
s1.remove(2)
print('After remove:',s1)
#discard()
s1.discard(8)
print('After discard:',s1)
#pop()
print('pop element is:',s1.pop())
print('After pop:',s1)
#clear()
s1.clear()
print('After clear:',s1)
s1.update({1,2,3,'ece','cse',2.5})
print('My New Set:',s1)
s2={1,2,4,5,6,'cse'}
print('set2 is:',s2)
#set operations
#union()
print('After union:',s1|s2)
print('After union:',s1.union(s2))
#insection()
print('After intersection:',s1&s2)
print('After intersection:',s1.intersection(s2))
#difference()
print('After differnece:',s1-s2)
print('After difference:',s1.difference(s2))
print('After differnece:',s2-s1)
print('After difference:',s2.difference(s1))
#symmetric_differnce()
print('After symmetric_differnece:',s1^s2)
print('After symmetric_difference:',s1.symmetric_difference(s2))
#insection_update()
s1.intersection_update(s2)
print('After intersection_update:',s1)
#difference_update()
s2.difference_update(s1)
print('After difference_update:',s2)
#symmetric_difference_update()
s1.symmetric_difference_update(s2)
print('After symmetric_difference_update:',s1)
#isdisjoint()
print(s1.isdisjoint(s2))
#issubset()
print(s2.issubset(s1))
#issuperset()
print(s1.issuperset(s2))
'''
OUTPUT:
<class 'dict'>
<class 'set'>
myset is: {1, 2, 3, 4, 5, 6}
My set length is: 6
After copy: {1, 2, 3, 4, 5, 6}
After add: {1, 2, 3, 4, 5, 6, 8}
After Update: {1, 2, 3, 4, 5, 6, 'cse', 8, 'ece'}
After remove: {1, 3, 4, 5, 6, 'cse', 8, 'ece'}
After discard: {1, 3, 4, 5, 6, 'cse', 'ece'}
pop element is: 1
After pop: {3, 4, 5, 6, 'cse', 'ece'}
After clear: set()
My New Set: {1, 2, 3, 2.5, 'ece', 'cse'}
set2 is: {1, 2, 4, 5, 6, 'cse'}
After union: {1, 2, 3, 2.5, 4, 'cse', 5, 6, 'ece'}
After union: {1, 2, 3, 2.5, 4, 'cse', 5, 6, 'ece'}
After intersection: {1, 2, 'cse'}
After intersection: {1, 2, 'cse'}
After differnece: {'ece', 2.5, 3}
After difference: {'ece', 2.5, 3}
After differnece: {4, 5, 6}
After difference: {4, 5, 6}
After symmetric_differnece: {'ece', 2.5, 3, 4, 5, 6}
After symmetric_difference: {'ece', 2.5, 3, 4, 5, 6}
After intersection_update: {1, 2, 'cse'}
After difference_update: {4, 5, 6}
After symmetric_difference_update: {1, 2, 4, 5, 'cse', 6}
False
True
True
'''
PROGRAMS ON FUNCTIONS:
#WRITE A PYTHON PROGRAM TO PERFORM ADDITION BETWEEN TWO
NUMBERS
USIN FUNCTION
def add(a,b):
"""this function display addition of two numbers"""
return(a+b)
a=int(input('Enter a value:'))
b=int(input('Enter b value:'))
result=add(a,b)
print('The addition of %d and %d is %d'%(a,b,result))
'''
OUTPUT:
Enter a value:10
Enter b value:20
The addition of 10 and 20 is 30
'''
'''
mylist=[]
size=int(input('Enter size of list:'))
for k in range(size):
mylist.append(int(input('Enter value:')))
print('My list is:',mylist)
result=findsum(mylist)
print('My list is:',mylist)
print('Result is:',result)
'''
OUTPUT:
Enter size of list:5
Enter value:-1
Enter value:2
Enter value:3
Enter value:-7
Enter value:5
My list is: [-1, 2, 3, -7, 5]
My list is: [0, 2, 3, 0, 5]
Result is: 10
'''