Unit - III
Unit - III
Itemsinthelistscanbeofdifferentdatatypes.
Eg: a=[10, 20, 30, 40]; b=[10, 20, “abc”, 4.5]
The following list contains a string, a float, an integer, and (lo!) another list:
['spam', 2.0, 5, [10, 20]]
Alistwithinanotherlistisnested.Alistthatcontainsnoelementsiscalledanempty
list;youcancreateonewithemptybrackets,[].
Asyoumightexpect,youcanassignlistvaluestovariables:
>>>cheeses = ['Cheddar', 'Edam', 'Gouda']
>>>numbers = [17, 123]
>>>empty = []
>>>print cheeses, numbers, empty
['Cheddar', 'Edam', 'Gouda'] [17, 123] []
Operations on list:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison
operations examples description
create a list >>> a=[2,3,4,5,6,7,8,9,10] in this way we can create
a
>>> print(a) list at compile time
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> print(a[0]) Accessing the item in the
Indexing 2 position 0
>>> print(a[8]) Accessing the item in the
10 position 8
>>> print(a[-1]) Accessing a lastelement
10 using negative indexing.
>>> print(a[0:3])
Slicing [2, 3, 4]
>>> print(a[0:]) Printing a part of the list.
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> print(a[2])
Listslices:
Listslicingisanoperationthatextractsasubsetofelementsfromanlistandpackages
them as anotherlist.
Syntax:
Listname[start:stop] Listname[start:stop:steps]
default start value is0
default stop value isn-1
[:] this will print the entirelist
[2:2] this will create a emptyslice
slices example description
a[0:3] >>> a=[9,8,7,6,5,4] Printingapartofalistfrom 0
>>>a[0:3] to2.
[9, 8, 7]
a[:4] >>> a[:4] Defaultstartvalueis0.so
[9,8,7,6] prints from 0 to3
a[1:] >>> a[1:] default stop value will
[8,7,6,5,4] be n-1. so prints from 1
to 5
a[:] >>>a[:] Prints the entire
[9, 8, 7, 6, 5, 4] list.
syntax:
list name.method name( element/index/list)
1. 2. 3.
4. 5. 6.
7. 8.
9. 10.
11. 12. 13.
4 >>>a=[0, 1, 2, 3, 8,5, 6, 7, 8,9] Returnstheindexof
a.index(element) >>>a.index(8) the first matched
4 item
5 >>> a=[1,2,3,4,5]
>>> sum(a) Sortitemsinalistin
sum() >>> print(a) ascendingorder
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]
6 >>>a.reverse()
Reverse the order
a.reverse() >>> print(a)
of items in the list
[8, 7, 6, 5, 4, 3, 2, 1, 0]
>>>a=[8, 7, 6, 5, 4, 3, 2, 1, 0]
7 a.pop() >>>a.pop() Removes and
0
>>>print(a)
=[8, 7, 6, 5, 4, 3, 2, 1] returns an element
at the last element
8 a.pop(index) >>>a.pop(0) Remove the
8
>>>print(a)
[7, 6, 5, 4, 3, 2, 1, 0] particular element
and return it.
>>>a=[7, 6, 5, 4, 3, 2, 1]
9 a.remove(element) >>>a.remove(1) Removes an item
>>> print(a) from the list
[7, 6, 5, 4, 3, 2]
>>>a=[7, 6, 5, 4, 3, 2,6]
10 a.count(element) >>>a.count(6) Returns the count
of
2 number of items
passed as an
Argument
>>>a=[7, 6, 5, 4, 3, 2]
11 a.copy() >>> b=a.copy() Returns a
>>> print(b) copy of the list
[7, 6, 5, 4, 3, 2]
>>>a=[7, 6, 5, 4, 3, 2]
12 len(list) >>>len(a) return the length of
6 the length
>>>a=[7, 6, 5, 4, 3, 2]
17 sum(list) >>> sum(a) return the sum of
27 element in a list
14 max(list) >>> max(a) return the maximum
element in a list.
7
15 a.clear() >>>a.clear() Removes all items
>>> print(a) from the list.
[]
16 del(a) >>> del(a) delete the entire
>>> print(a) list.
Error: name 'a' is not
defined
Listloops:
1. Forloop
2. Whileloop
3. InfiniteloopL
istusingForLoop:
TheforloopinPythonisusedtoiterateoverasequence(list,tuple,string)orother
iterableobjects.
Iterating over a sequence is calledtraversal.
Loopcontinuesuntilwereachthelastiteminthesequence.
Thebodyofforloopisseparatedfromtherestofthecodeusingindentation.
Syntax:
forvalinsequence:
Infinite Loop
Aloopbecomesinfiniteloopiftheconditiongivenneverbecomesfalse.Itkeepson
running.Suchloopsarecalledinfiniteloop.
Example Output:
a=1 Enter the number 10
while (a==1): you entered:10
n=int(input("enter the number")) Enter the number 12
print("you entered:" , n) you entered:12
Enter the number 16
you entered:16
Mutability:
Lists are mutable. (can bechanged)
Mutabilityistheabilityforcertaintypesofdatatobechangedwithoutentirely
recreatingit.
Anitemcanbechangedinalistbyaccessingitdirectlyaspartoftheassignment
statement.
Usingtheindexingoperator(squarebrackets[])ontheleftsideofanassignment,
oneofthelistitemscanbeupdated.
Example description
Example Output:
a= [1, 2, 3 ,4 ,5]
b=a
print (b) [1, 2, 3, 4, 5]
a is b True
a[0]=100
print(a) [100,2,3,4,5]
print(b) [100,2,3,4,5]
Inthisasinglelistobjectiscreatedandmodifiedusingthesubscriptoperator.
Whenthefirstelementofthelistnamed“aˮisreplaced,thefirstelementofthelist
named “bˮ is alsoreplaced.
Thistypeofchangeiswhatisknownasasideeffect.Thishappensbecauseafter
theassignmentb=a,thevariablesaandbrefertotheexactsamelistobject.
Theyarealiasesforthesameobject.Thisphenomenonisknownasaliasing.
Topreventaliasing,anewobjectcanbecreatedandthecontentsoftheoriginal
canbecopiedwhichiscalledcloning.
Clonning:
Toavoidthedisadvantagesofcopyingweareusingcloning.
Creatingacopyofasamelistofelementswithtwodifferentmemorylocationsiscalledcloning.
Changesinonelistwillnotaffectlocationsofaotherlist.
Cloningisaprocessofmakingacopyofthelistwithoutmodifyingtheoriginallist.
1. Slicing
2. list()method
3. copy()method
a=[1,2,3,4,5]
>>>b=a.copy()
>>> print(b)
[1, 2, 3, 4, 5]
>>>aisb
False
List as parameters:
Inpython,argumentsarepassedbyreference.
Ifanychangesaredoneintheparameterwhichreferswithinthefunction,thenthe
changesalsoreflectsbackinthecallingfunction.
Whenalisttoafunctionispassed,thefunctiongetsareferencetothelist.
Passingalistasanargumentactuallypassesareferencetothelist,notacopyofthelist.
Sincelistsaremutable,changesmadetotheelementsreferencedbytheparamete
r changethesamelistthattheargumentisreferencing.
Example 1`: Output
def remove(a): [2,3,4,5]
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
Example 2: Output
def inside(a): inside [11, 12, 13, 14,15]
for i in range(0,len(a),1): outside [11, 12, 13, 14, 15]
a[i]=a[i]+10
print(“insideˮ,a)
a=[1,2,3,4,5]
inside(a)
print(“outsideˮ,a)
Example 3 output
def insert(a): [30, 1, 2, 3, 4, 5]
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)
Tuple:
Atupleissameaslist,exceptthatthesetofelementsisenclosedinparenthesesinstead
of squarebrackets.
Atupleisanimmutablelist.i.e.onceatuplehasbeencreated,youcan'taddelementsto
atupleorremoveelementsfromthetuple.
Buttuplecanbeconvertedintolistandlistcanbeconvertedintotuple.
methods example description
list( ) >>> a=(1,2,3,4,5) it convert the given tuple
>>> a=list(a) into list.
>>> print(a)
[1, 2, 3, 4, 5]
tuple( ) >>> a=[1,2,3,4,5] it convert the given list
into
>>> a=tuple(a) tuple.
>>> print(a)
(1, 2, 3, 4, 5)
Benefit of Tuple:
Tuples are faster thanlists.
Iftheuserwantstoprotectthedatafromaccidentalchanges,tuplecanbeused.
Tuplescanbeusedaskeysindictionaries,whilelistscan't.
Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison
Operations examples description
Creating the tuple with
Creating a tuple >>>a=(20,40,60,ˮappleˮ,ˮballˮ) elements of different
data
types.
>>>print(a[0]) Accessing the item in the
Indexing 20 position 0
>>> a[2] Accessing the item in the
60 position 2
Slicing >>>print(a[1:3]) Displayingitemsfrom 1st
(40,60) till 2nd.
Concatenation >>> b=(2,4) Adding tuple
elementsat
>>>print(a+b) theend of
anothertuple
>>>(20,40,60,ˮappleˮ,ˮballˮ,2,4) elements
Repetition >>>print(b*2) repeating the tuple in n no
>>>(2,4,2,4) of times
>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a
Membership True Returns True if element is
>>> 100 in a present in tuple.
Otherwise
False returns false.
>>> 2 not in a
False
>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4) ReturnsTrueifallelements
Comparison
>>> a==b in both elements are
False same. Otherwise
>>>a!=b returnsfalse
True
Tuple methods:
Tupleisimmutablesochangescannotbedoneontheelementsofatupleonceitis
assigned.
methods example description
a.index(tuple) >>> a=(1,2,3,4,5) Returns the index of the
>>>a.index(5) first matched item.
4
a.count(tuple) >>>a=(1,2,3,4,5) Returns the count of the
>>>a.count(3) given element.
1
len(tuple) >>>len(a) return the length of the
5 tuple
min(tuple) >>> min(a) return the minimum
1 element in a tuple
max(tuple) >>> max(a) return the maximum
5 element in a tuple
del(tuple) >>> del(a) Delete the entire tuple.
TupleAssignment:
Tupleassignmentallows,variablesontheleftofanassignmentoperatorandvaluesof
tupleontherightoftheassignmentoperator.
Multipleassignmentworksbycreatingatupleofexpressionsfromtherighthand
side, and a tuple of targets from the left, and then matching each expression
to a target.
Becausemultipleassignmentsusetuplestowork,itisoftentermedtuple
assignment.
Uses of Tuple assignment:
Itisoftenusefultoswapthevaluesoftwovariables.
Example:
Swapping using temporary variable: Swapping using tuple assignment:
a=20 a=20
b=50 b=50
temp = a (a,b)=(b,a)
a=b print("value after swapping is",a,b)
b = temp
print("value after swapping is",a,b)
Multiple assignments:
Multiple values can be assigned to multiple variables using tuple assignment.
>>>(a,b,c)=(1,2,3)
>>>print(a) 1
>>>print(b)
2
>>>print(c)
3
Tuple as returnvalue:
ATupleisacommaseparatedsequenceofitems.
Itiscreatedwithorwithout().
Afunctioncanreturnonevalue.ifyouwanttoreturnmorethanonevaluefroma
function.wecanusetupleasreturnvalue.
Example1: Output:
def div(a,b): enter a value:4
r=a%b enter b value:3
q=a//b reminder: 1
return(r,q) quotient: 1
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
Example2: Output:
defmin_max(a): smallest: 1
small=min(a) biggest: 6
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)
Tuple as argument:
Theparameternamethatbeginswith*gathersargumentintoatuple.
Example: Output:
defprintall(*args): (2, 3, 'a')
print(args)
printall(2,3,'a')
Dictionaries:
Dictionaryisanunorderedcollectionofelements.Anelementindictionaryhasakey:
valuepair.
Allelementsindictionaryareplacedinsidethecurlybracesi.e.{}
ElementsinDictionariesareaccessedviakeysandnotbytheirposition.
Thevaluesofadictionarycanbeanydatatype.
Keysmustbeimmutabledatatype(numbers,strings,tuple)
Operations on dictionary:
1. Accessing anelement
2. Update
3. Addelement
4. Membership
Operations Example Description
Creating a >>> a={1:"one",2:"two"} Creating the dictionary with
dictionary >>> print(a) elements of different data types.
{1: 'one', 2: 'two'}
accessing an >>> Accessing the elements by using
a[1]
element 'one' keys.
>>>
a[0]
KeyError: 0
Update >>> a[1]="ONE" Assigning a new value to key. It
>>> print(a) replaces the old value by new
value.
{1: 'ONE', 2: 'two'}
add element >>> a[3]="three" Add new element in to the
>>> print(a) dictionary with key.
{1: 'ONE', 2: 'two', 3: 'three'}
membership a={1: 'ONE', 2: 'two', 3: 'three'} Returns True if the key is present
in
>>>1 in a dictionary. Otherwise returns
false.
True
>>> 3 not in a
False
Methodsindictionary:
Advancedlistprocessing:
ListComprehension:
Listcomprehensionsprovideaconcisewaytoapplyoperationsonalist.
Itcreatesanewlistinwhich each elementistheresultofapplyingagivenoperationina
list.
Itconsistsofbracketscontaininganexpressionfollowedbya“forˮclause,thenalist.
Thelistcomprehensionalwaysreturnsaresultlist.
Syntax
list=[ expression for item in list if conditional ]
Programs on matrix:
Matrix addition Output
a=[[1,1],[1,1]] [3, 3]
b=[[2,2],[2,2]] [3, 3]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
c[i][j]=a[i][j]+b[i][j]
for i in c:
print(i)
def divide(x):
if len(x) == 0 or len(x) == 1:
return x
else:
middle = len(x)//2
a = divide(x[:middle])
b = divide(x[middle:])
return merge(a,b)
x=[38,27,43,3,9,82,10]
c=divide(x)
print(c)
Histogram Output
def histogram(a): ****
for i in a: *****
sum = '' *******
while(i>0): ********
sum=sum+'#' ************
i=i-1
print(sum)
a=[4,5,7,8,12]
histogram(a)
Calendar program Output
import calendar enter year:2017
y=int(input("enter year:")) enter month:11
m=int(input("enter month:")) November 2017
print(calendar.month(y,m)) Mo Tu We Th Fr Sa Su
12345
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
PART - A
1. What isslicing?
2. Howcanwedistinguishbetweentuplesandlists?
3. Whatwillbetheoutputofthegivencode?
a.List=[‘pʼ,ʼrʼ,ʼiʼ,ʼnʼ,ʼtʼ,]
b. Print list[8:]
4. Givethesyntaxrequiredtoconvertanintegernumberintostring?
5. List is mutable.Justify?
6. DifferencebetweendelandremovemethodsinList?
7. Difference between pop and remove inlist?
8. Howarethevaluesinatupleaccessed?
9. What is a Dictionary inPython
10. Define listcomprehension
11. Write a python program using listlooping
12. Whatdoyoumeantbymutabilityandimmutability?
13. DefineHistogram
14. DefineTupleandshowitisimmutablewithanexample.
15. statethedifferencebetweenaliasingandcloninginlist
16. what is listcloning
17. what is deepcloning
18. statethedifferencebetweenpopandremovemethodinlist
19. create tuple with singleelement
20.swaptwonumberswithoutusingthirdvariable
21. define properties of key indictionary
22. howcanyouaccesselementsfromthedictionary
23. differencebetweendeleteandclearmethodindictionary
24.Whatissqueezinginlist?giveanexample
25. Howtoconvertatupleintolist
26. Howtoconvertalistintotuple
27. Create a list using listcomprehension
28. Advantage of listcomprehension
29. Whatistheuseofmap()function.
30.Howcanyoureturnmultiplevaluesfromfunction?
31. what is sorting and types ofsorting
32. Findlengthofsequencewithoutusinglibraryfunction.
33.how to pass tuple asargument
34.how to pass a list asargument
35. whatisparameterandtypesofparameter
36. howcanyouinsertvaluesintodictionary
37. what is key valuepair
38. mentiondifferentdatatypescanbeusedinkeyandvalue
39. whataretheimmutabledatatypesavailableinpython
40.Whatistheuseoffromkeys()indictioanary.
PART-B
1. Explain in details about listmethods
2. Discuss about operations inlist
3. What is cloning? Explainit with example
4. What is aliasing? Explain withexample
5. Howcanyoupasslistintofunction?Explainwithexample.
6. Explaintuplesasreturnvalueswithexamples
7. write a program for matrixmultiplication
8. write a program for matrixaddition
9. write a program for matrixsubtraction
10. write a program for matrixtranspose
11. write procedure for selectionsort
12. explain merge sort with anexample
13. explain insertion withexample
14. Explainindetailaboutdictionariesanditsmethods.
15. Explainindetailaboutadvancedlistprocessing.