0% found this document useful (0 votes)
13 views30 pages

Unit - III

Unit III covers compound data types in Python, focusing on lists, tuples, and dictionaries. It details list operations, methods, and advanced processing techniques such as list comprehensions, along with examples of sorting algorithms. The unit also discusses mutability, aliasing, and cloning of lists to manage data effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views30 pages

Unit - III

Unit III covers compound data types in Python, focusing on lists, tuples, and dictionaries. It details list operations, methods, and advanced processing techniques such as list comprehensions, along with examples of sorting algorithms. The unit also discusses mutability, aliasing, and cloning of lists to manage data effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

UNIT III

COMPOUND DATA: LISTS, TUPLES, DICTIONARIES


Lists,listoperations,listslices,listmethods,listloop,mutability,aliasing,cloninglists,
list parameters; Tuples, tuple assignment, tuple as return value; Dictionaries:
operationsandmethods;advancedlistprocessing-listcomprehension,Illustrative
programs:selectionsort,insertionsort,mergesort,quicksort.
Lists
 Listisanorderedsequenceofitems.Valuesinthelistarecalledelements/items.
 Itcanbewrittenasalistofcomma-separateditems(values)betweensquare
brackets[].

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]

>>>b=[20,30] Adding and printingthe


Concatenation >>> print(a+b) items of two lists.
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
>>> print(b*3) Createamultiplecopiesof
Repetition [20, 30, 20, 30, 20, 30] the same
list.

>>> print(a[2])

4 Updating the list using


Updating >>> a[2]=100 index value.
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
>>> 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 list. Otherwise
False returns false.
>>> 2 not in a
False
>>> a=[2,3,4,5,6,7,8,9,10]
>>>b=[2,3,4] Returns True if all
Comparison
elements
>>> a==b in both elements are same.
False Otherwise returns false
>>> a!=b
True

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.

slices example description

a[2:2] >>> a[2:2] print an empty slice


[]
a[0:6:2] >>> a=[9,8,7,6,5,4] Slicinglistvalueswithstep
>>>a[0:6:2] size2.(fromindex[0]to2nd
[9, 7, 5] element and from that
>>>a[0:6:3] positiontonext2ndelement
[9,6]

syntax:
list name.method name( element/index/list)

syntax example description


1 >>>a=[1,2,3,4,5]
>>>a.append(6) Addanelementto
a.append(element) >>> print(a) theendofthelist
[1,2,3,4,5,6]
2 a.insert(index,element) >>>a.insert(0,0) Insertanitematthe
>>> print(a) definedindex
[0, 1, 2, 3, 4, 5, 6]
3 a.extend(b) >>> a=[1,2,3,4,5]
>>> b=[7,8,9]
>>>a.extend(b) Addallelementsofa
>>> print(a) list to the another
[0, 1, 2, 3, 4, 5, 6, 7, 8,9] list
Listmethods:

Python provides methods that operate on lists.

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:

Accessing element output


a=[10,20,30,40,50] 10
for i in a: 20
print(i) 30
40
50
Accessing index output
a=[10,20,30,40,50] 0
for i in range(0,len(a),1): 1
print(i) 2
3
4
Accessing element using range: output
a=[10,20,30,40,50] 10
for i in range(0,len(a),1): 20
print(a[i]) 30
40
50
List using While loop
 ThewhileloopinPythonisusedtoiterateoverablockofcodeaslongasthetest
expression (condition) istrue.
 Whentheconditionistestedandtheresultisfalse,theloopbodywillbeskippedandthe
firststatementafterthewhileloopwillbeexecuted.
Syntax:
while (condition):
body ofwhile

Sum of elements in list Output:


a=[1,2,3,4,5] 15
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)

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

>>> a=[1,2,3,4,5] changing single element


>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
>>> a=[1,2,3,4,5] changing multiple element
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
>>> a=[1,2,3,4,5] The elements from a list can also be
>>> a[0:3]=[ ] removed by assigning the empty list to
>>> print(a) them.
[4, 5]
>>> a=[1,2,3,4,5] The elements can be inserted into a list
by
>>> a[0:0]=[20,30,45] squeezing them into an empty slice at
the
>>> print(a) desired location.
[20,30,45,1, 2, 3, 4, 5]
Aliasing(copying):
 Creatingacopyofalistiscalledaliasing.


Whenyoucreateacopyboththelistwillbehavingsamememorylocation.

changesinonelistwillaffectanotherlist.

Alaising refers to having different names for same list values.

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

clonning using Slicing


>>>a=[1,2,3,4,5]
>>>b=a[:]
>>>print(b)
[1,2,3,4,5]
>>>a is b
False #because they have different memorylocation
clonning using List( ) method
>>>a=[1,2,3,4,5]
>>>b=list
>>>print(b)
[1,2,3,4,5]
>>>a is b
false
>>>a[0]=100
>>>print(a)
>>>a=[100,2,3,4,5]
>>>print(b)
>>>b=[1,2,3,4,5]
clonning using 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:

Method Example Description

a.copy( ) a={1: 'ONE', 2: 'two', 3: 'three'} It returns copy of the


>>> b=a.copy() dictionary. here copy
of
>>> print(b) dictionary ʼaʼ get stored
{1: 'ONE', 2: 'two', 3: 'three'} in to dictionary ‘bʼ
a.items() >>>a.items() Return a new view of
dict_items([(1,'ONE'),(2,'two'),(3, the dictionary's items.
It
'three')]) displays a list of
dictionaryʼs (key,
value)
tuple pairs.
a.keys() >>>a.keys() It displays list of keys
in
dict_keys([1, 2, 3]) a dictionary
a.values() >>>a.values() It displays list of values
dict_values(['ONE', 'two', 'three']) in dictionary
a.pop(key) >>>a.pop(3) Remove the element
'three' with key and return its
>>> print(a) value from the
{1: 'ONE', 2: 'two'} dictionary.
setdefault(key,value >>>a.setdefault(3,"three") If key is in the
) 'three' dictionary, return its
>>> print(a) value. If key is not
{1: 'ONE', 2: 'two', 3: 'three'} present, insert key with
>>>a.setdefault(2) a value of dictionary
and
'two' return dictionary.
a.update(dictionary) >>> b={4:"four"}
It will add the
>>>a.update(b)
dictionary
>>> print(a) with the existing
{1: 'ONE', 2: 'two', 3: 'three', 4: dictionary
'four'}
fromkeys() >>> key={"apple","ball"} It creates a dictionary
>>> value="for kids" from key and values.
>>> d=dict.fromkeys(key,value)
>>> print(d)
{'apple': 'for kids', 'ball': 'for kids'}
len(a) a={1: 'ONE', 2: 'two', 3: 'three'} It returns the length of
>>>lena(a) the list.
3
clear() a={1: 'ONE', 2: 'two', 3: 'three'} Remove all elements
>>>a.clear() form the dictionary.
>>>print(a)
>>>{ }
del(a) a={1: 'ONE', 2: 'two', 3: 'three'} It will delete the entire
>>> del(a) dictionary.

Difference between List, Tuples and dictionary:

List Tuples Dictionary


A list is mutable 0A tuple is immutable A dictionary is mutable
Lists are dynamic Tuples are fixed size in nature In values can be of any
data type and can
repeat, keys must be
of
immutable type
List are enclosed in Tuples are enclosed in parenthesis Tuples are enclosed in
()
brackets[ ] andtheir and cannot be updated curly braces { } and
elements and size consist of key:value
can be changed
Homogenous Heterogeneous Homogenous
Example: Example: Example:
List = [10, 12, 15] Words = ("spam", "egss") Dict = {"ram": 26,
"abi":
Or 24}
Words = "spam", "eggs"
Access: Access: Access:
print(list[0]) print(words[0]) print(dict["ram"])
Cancontainduplicate Can contain duplicate elements. Cant contain duplicate
elements Faster compared to lists keys, but can contain
duplicate values
Slicing can be done Slicing can be done Slicing can't be done
Usage: Usage: Usage:
 List is used ifa  Tuple can be used whendata  Dictionary isused
collection of data cannot be changed. when a logical
that
doesnt need  Atupleisusedincombination association between
random
access. with a dictionary i.e.a tuple might key:value pair.
 List is usedwhen represent a key.  When in need offast
data can be lookup for data, based
modified
frequently on a custom key.
 Dictionary isused
when data is being
constantly modified.

Advancedlistprocessing:
ListComprehension:
 Listcomprehensionsprovideaconcisewaytoapplyoperationsonalist.
 Itcreatesanewlistinwhich each elementistheresultofapplyingagivenoperationina
list.

 Itconsistsofbracketscontaininganexpressionfollowedbya“forˮclause,thenalist.
 Thelistcomprehensionalwaysreturnsaresultlist.
Syntax
list=[ expression for item in list if conditional ]

List Comprehension Output


>>>L=[x**2 for x in range(0,5)] [0, 1, 4, 9, 16]
>>>print(L)
>>>[x for x in range(1,10) if x%2==0] [2, 4, 6, 8]
>>>[x for x in 'Python Programming' if x in ['a','e','i','o','u']] ['o', 'o', 'a', 'i']
>>>mixed=[1,2,"a",3,4.2] [1, 4, 9]
>>> [x**2 for x in mixed if type(x)==int]

>> >[x+3 for x in [1,2,3]] [4, 5, 6]

>>> [x*x for x in range(5)] [0, 1, 4, 9, 16]

>>> num=[-1,2,-3,4,-5,6,-7] [2, 4, 6]


>>> [x for x in num if x>=0]

>>>str=["this","is","an","example"] ['t', 'i', 'a', 'e']


>>> element=[word[0] for word instr]
>>> print(element)
Nestedlist:
List inside another list is called nested list.
Example:
>>> a=[56,34,5,[34,57]]
>>>a[0]
56
>>>a[3]
[34, 57]
>>>a[3][0]
34
>>>a[3][1]
57
Cross product of two sets:

>>> colours = [ "red", "green", "yellow", "blue" ]


>>> things = [ "house", "car", "tree" ]
>>> coloured_things = [ (x,y) for x in colours for y in things ]
>>> print coloured_things
[('red', 'house'), ('red', 'car'), ('red', 'tree'), ('green', 'house'), ('green', 'car'), ('green', 'tree'), ('yellow', 'house'),
('yellow', 'car'), ('yellow', 'tree'), ('blue', 'house'), ('blue', 'car'), ('blue', 'tree')]
>>>

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)

Matrix multiplication 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)):
for k in range(len(b)):
c[i][j]=a[i][j]+a[i][k]*b[k][j]
for i in c:
print(i)

Matrix transpose Output


a=[[1,3],[1,2]] [1, 1]
c=[[0,0],[0,0]] [3, 2]
for i in range(len(a)):
for j in range(len(a)):
c[i][j]=a[j][i]
for i in c:
print(i)
Illustrative programs:
Selection sort Output
a=input("Enter list:").split() Enter list:23 78 45 832 56
a=list(map(eval,a)) [8,2 3, 32, 45,56, 78]
for i in range(0,len(a)):
smallest = min(a[i:])
sindex= a.index(smallest)
a[i],a[sindex] = a[sindex],a[i]
print (a)

Insertion sort output


a=input("enter a list:").split()
a=list(map(int,a))
for i in a: enter a list: 8 5 7 1 9 3
j = a.index(i) [1,3,5,7,8,9]
while j>0:
if a[j-1] > a[j]:
a[j-1],a[j] = a[j],a[j-1]
else:
Break
j = j-1
print (a)
Merge sort output
def merge(a,b):
c = [] [3,9,10,27,38,43,82]
while len(a) != 0 and len(b) != 0:
if a[0] < b[0]:
c.append(a[0])
a.remove(a[0])
else:
c.append(b[0])
b.remove(b[0])
if len(a) == 0:
c=c+b
else:
c=c+a
return c

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.

You might also like