You are on page 1of 25

Data Structures in Python

Lists : Defining lists, accessing values in list, deleting values in list, updating lists, Basic List Operations, Built-in List
functions, Tuples : Accessing values in Tuples, deleting values in Tuples, and updating Tuples, Basic Tuple
Operations,
Built-in Tuple functions, Sets ;
Accessing values in Set, deleting values in Set, Basic Set Operations, Built-in Set
functions, Dictionaries : Accessing values in Dictionary, deleting values in Dictionary, Basic Dictionary Operations,
Built-in Dictionary functions.

3.1

GO.3.1.1 Write a python program to create student name database using list and perform operations, like add,
delete, search student name in the list. (4 Marks)..... ................ g_3

3.2.4 Range S|ice..,.,........ .................. 3-6

Go.3.4.1WhatiSthediffereneebetweenlistsandtuples?(4.Marks)

3.4,3Adding/Removing/DeletingElementsoftheTuple''
with
3-2 Data Structures in
____-_-__.......'.....:____

GQ. 3.6.1 What is the difference between lists and types ? (4


Marks) .....3-14

3.7.2 Accessing Elements in Set............


....3_15

cQ. 3.9_1 Define dictionary with the help of example.


(2 Marks)..... ........3-.lg

GQ. 3.9.2 Explain syntax of dictionary with the help of


example. (2 Marks) .................3_20
3.9.2 Accessing Elements of A Dictionar
...... g-21
GQ. 3.9.3 ,Write a python program to go
through dictionary using for loops. (4 Marks)......... ............ g_21

GQ. 3.9.4 Write a python program to add a key to a dictionary.


(4 Marks)..... ..............5-21
3 9'4 Remove/delete an Element of Dictionary ..................... ....................g_22
Go' 3'9'5 Explain two methods to remove an element from a dictionary with
example. (4 Marks)..... ...................3-22

GQ. 3.10.1 Explain any two dictionary methods


with example. (2 Marks) ...................... g_23

GQ. 3.11.1 Write a python program to calculate


length of a dictionary. (2 Marks) .........5_24

I- Neo Pulrlications..... ..,.


h - _. W ere,4 u th ors hr,rplrc ir"* *,: *
....4 SA CEIN SII4II Yen tu re
with (MSBTE - 6'n Sem. - Data Structures in
)) 3.1 List Data Type

| .,. ' :
like add, delete, s:earch student name iw the tist. (+ Mad*)
As aforementioned in unit I Data type is classification or categorization of data items. list is one of the data
structure used in the python. A list represents a collection of items. These iterns are put in square brackets []
separated by commas. This representation of list is very similar ro iuray representation of C. Lists are
expressed in following format :

List = [iteml,item2,......]
- The only major difference is, in C all the array elements are homogeneous. But there is no such restriction
on
items in the List of python.

- The items in thc list can be heterogeneous (i.c. they can be of different data types). List data structure is
used
in the applications u,here we need data item of different types:

its 3.1.1 Creafion of Lists

- As in python we don't need to declare type of variable. We can create a Iist by simply writing list name and
assigning irems of list in squar.e brackets.

In ihe example, Fig. 3.1.1 , list of name "listl", listl consist of 7 items among these T items 4 items are int,
one is of type float and 2 are of string type.

Ttpe o/'/t^*l fu '7Lrr"


{ qt 1r., l'r 1 i
]-4JL4'":_rr_!.r,,$, ,,1 - ' -,er:'
,}ffii. ,
, jnhn,
,UI,;l
-rt., ...li'!
I 1
crr,ir:f
1.. * liat?
+ **Jt*

i.;*a*i listf )

In, E, 3r At nsa*r', 'j*h**, ?S.*J

- r e-*

Fig. 3.1.1 : Creation of list

b. 3.1.2 Accessing Elements of List


We can access the list elements by their index, as shown in the Fig. 3.1.2. The 4e element in the "listl" is
"4" o we can access it using its index. List index start with '0' hence index of the 4th element is
3.

p*.iriL }ietl{ _sl

Fig. 3.1.2 : Accessing element of the tist

Teeh-Neo Pirblications..,....."..Wrere Autltots inspie innotation ....4 SACIilt SIIAII lbnture


[b] programming with pvthon (MSBTE - 6th Sem. - Comp) 3-4 Data Structures rn Pythm

)s. 3.1.3 Adding Elements in the List


We can add elements in the list by using append 0 function, in this we need to provide .l"*"nt as parameter
is
to the append function. Demonstration of the append function is shown in Fig. 3.1.3. the newly added element
placed at the end of list. In Fig. 3.1.3 we have added element "Mike" in the list "listl"'

f .ie1.1=|.1 1: : ,^nrt\&ff'-'dnhf
.L-r*t*t'^o; iEel'l , '-'-';'"1
,r 'l
'r-'i''i
iist1- append ( ':'t:ke ' i
^0. 1
i. -,.1*. jlf i *+"1
L4
Fr; ;,: i.

[3., 2, 3o 4,'salrr', 'jshn', ?8.*r ':'ii-ke'l


Fig.3.1.3 : Adding elernent in the list

)3. 3.1.4 RemovinglDeleting Element from List

We can delete/remove element from list1 . espend: ' Itike' :

the list using remove0, in this we


need to provide index of the eiement listL
or name ol- lhe element as argtlment.
[1, Zr 3" 4r 'gagt'.. ' johr:', ?S"?, 'rdike']
In the following example we have
provided index of the element 'lvlike' 1istl,.reJn*$e, ListI ['i ] r

to thc remove function i.e. listl[7],


shown in Fig. 3.1.4. liEtl
[]-, 3* 3i 4r sfim r 'jchft', ?S"91

Fig. 3.1.4 : Removing/deleting element of list hy providing its index

By providing element name as argurnent to the remove l'unction. here we have given element 'Mike' as thc
parameter to the remove function. shown in Fig. 3.i.5'

Ij-*tI "
&pp€fld,:' L.tik#',

1:st 1

i1, Z,r 3r *' 'gait!', 'johrt', ?8.$' 'l{Akg'1

l ist i . remove 'H 1it3 '

'1.:E+l

i1, t,3, *, 's&fl!', 'john'* ?E.SI

Fig. 3.1.5 : Removinfdeleting list elernent try providing it name


;rt h n ....A S:4ttIIN SII4II lbnture
Tech-Neo Publications.."....'...V'here Autltot's inspir.- innot
with 3-5 Data Structures in

3.2 Basic List Operations


The operbtors are explained below with the help of example :

--t
0perators Descrlption

+ Concatenation

Repetition

tl Slice

[:] Range Slice

1n Membership

)8. 3.2.1 Concatenation


This operator helps us to concaienate either sides of the operator. Operator is symbolized using "+" sign.
You can concatenate lists using this operator. Fig. 3;2.! there are two lists defined namely lis0 and hst3.
The concatenation operator adds these two lists.

1J-rr'1,1
IT5 Ld,," II5 ^rr
tD

[1, r, I, z, 'Ailne' 3, 4, 5,5, ',Siena' j


Fig. 3.2.1 : List concatenation

b. 3.2.2 Repetition
The repetition operator creates multiple copies of the list. Operator is symbolized using "*" sign' You can
use this operator for repetition purpose. In example, Fig. 3.2.2 "Lis2" is repeated for two times using
repetition operator.

Li.st2,+t

[1-1, ?,?, 'Aftna', ?t, 1-1, ].3, 'Afinfi', 78]

Fig. 3.2.2 : List repetition

Tech-Neo Puhlieations..,.. ......Wherc Authors in spirc innowtion ...-1 ilLfln silUI lbnture
tEi :-:,3ramming with Python (MSBTE - 6th Sem. - Comp) 3-6 Data Structures in Python

1 :"2.3 Slice

l::s operation gives us character from given index. Operator is symbolized using "[ ]" brackets. You can
-:lteve any element using this operator.
-. erample, Fig. 3.2.3 we have accessed the third element of the list, with its index i.e. 2.

i r' A.:iXi

n t
*fi,rl[&

Fig. 3.2.3 : List Slicing

3 3,2.4 Range Slice

This operation retums the characters from a specified range. Operator is symbolized using "[ : ]" sign. You
can retrieve range of the elements using this operator.

In example, Fig. 3.2.4 range slice operation is performed. This operation uses the concept of half open
interval. This means 1 is inclusive and 3 is exciusive. ( i and 3 are indices)

all[ I :31
Inclusive Exclusive }*stB i J-.:i :i

It will access list elements from start i.e. from 1" indexed item of list f q +t
and will go up to 2nd indeied item as this is half open interval (that
td* 5.tr

mcans 3'd index itcm will be excludcd). Fig,3.2.4: List range slicing

)8. 3.2.5 Membership


This operation is used to check whether that parlicular element belongs to the list or not. Operator is
symbolized using "in" word.

In example, Fig.3.2.5 and3.2.6membership operation is performed.

If the element is present in the list then result will be true otherwise l'alse.

st= I U r 3, 4, 'An na 3 " Anna * i,n 3ist


3.i.
=, ,'
True
2 i.n Li.st 5 :LT* .L 3- SE.

True Faf-se
Fig. 3.2.5 : List membership Fig. 3.2.6 : List memtrership

Tech-Neo Pulrlications,.... ......Were Authors inspire innovation ...-4 SACIil]Y SHAH Yeature
with Python (IVSBTE - 6'n Sem. - Comp) Data Structures in
)H 3.3 Built-in List Methods
There are various built-in functions / methods provide<l by python, list is as follows. clemgnstration as shou,n
in Fig. 3.3.1.
Methods Description
append Append ob.iect to the end of the list.
clear Remove all iterns fu'om list
COPY' R ct
1'n-a 1u1)j_i',],.1',
count
l1:ry lyg!:,- ?_l "._.1"iry:t@---
extend
!,:::_tbLlf $1c3|]inqeicmenrsp."uia*.ru[.,r,-.rttothe;;;o".,r,-"d
inclex R*to* in.l"^ of fir*1o."o**n*" of th* *I"*rr,t pro.,rid*d u, u.g.rffi
lnsert Insert element before index, here inclex and element are provided as argument to the insert
function i.e. insert (index, elemsnt)
pop Remol,e and return item at index
remove Remove first occurrence of, element
revelse Reverse the list

sort Sort the list

list}r [,, ",.,,r,il, :.. ::, .::ala' ]


jist4= i., i, i, ;, ;

list3, #xt€r,j{ lisr,t }


:,.:-:i'1lp
f .&. :i
p.rTi
L..LLrLv
ja,1 "iq1 ir.r
_6JL at' lirfi r
"\ ,-4JldJ

?hs *xta#*d iitt is: il, l, ], 4l I,5* 'iliana', 5, 3, 8, :r il


i ,a**^ : ..;' 'i
1
.r4.D rT* |f rr'
;.r ":I +, n J ,i.t 1J

1r"i+l 'Tnt ind*r, ci thr *L*m*n{u, '{:


i. t:
!l
i*; u', list4- i*dex{;l}

Tfu* ,ind*s ,*f t,h* *lsnm*t 3, is: $

$f,*t*..fpit4 rX 'e #*tr*:*' 1", r,t' .tii'* i J r.;.,'j{r r


*E' u, ul'l
Iitt5,*[ r'b','f ' r' fi
3irtS. r*fisve{ 'i'}
I:i ;;:i- 'l j.si i{trr" r*ff*,,ie *ferg,ti*,l iS: ' , iiStS

Li*t after rellls\i* *:Ferxti*rl ir: l*it,u 'r,, 's*o ,d,i

Tech-Neo Pulrli cations.......... Wlherc A uthon insgtire inaot a tion


" ....1 SACIIIN SIIAII Yenture
E-l
Hi erogrr*ming
- with Python (MSBTE - 6tn S"*. - Comp; 3-8 Data Structures in Python

1ist1=[tr ,3 r412, ?, 'sam' , ' john'r78.S]


2
priftti 'The elemet 2 j.s sccur"ed ' ,lj.stl. countt 3 ), 't j.mes ' ,i

The elemet 2 is occured 3 times


1ist1=[1, 3, 3r4, * saftl',' john' r7&. S]
1ist1, reverse', ,i
print { J. i st3. )
[78.9, ' john'., 'sarr']' , 4, 3, ?-, 1-l
list1=[tr], 3r4r' saffi ' r' jCIhn' r7*" gt]
prlnt, 'The index of element 3 is:',list1.index(3),
The index of element 3 is: 2
1ist2=[t " 1,2. 3r' Anr']a', 7*l
1ist5=iist2. copy( )
pnlnt(' New lj.st j.s :', 1i.st5)
Nerv list is: ,11.L, 2.2, 'Anna', 78]
1ist2=15.1,4, 3,6. 1,2.1,1. 1,2. ?, ?*J
1ist2. sort r .;

pni"nt ( ' The sorted list is : ' , list2 )

The sorted list is: []..1, 2.7, 2.2, 4.3, 5.1, 5.1, 781
1ist2=11 " 1, 2" ?r'Anna' r7S]
1ist2,pop(-1)
prtni{ 'The aftei pap is: ' ,1ist2)
The l"ist after psp is; [1,3, 2,2, 'Anna']
,,

I ist3= [ I . 1" j',H'li ;.:'l.$#fi#,i;..ry''J,,,l,r.''r]1,


1i.ste"..t].]eer{}..'...
pr int {' The',1Ergt=L':A'#t i' Ct#,r:,l.. is:'rIist2i
T,he List after clear is: []
Fig. 3.3.1 : Listbuilt-in function

Tech-Neo Pulrlications..... ......Were A uthors iaspire inn ova tio n ....A SACIIIN SIIAII lbntare
Data Structures in

Itr'El /trI
[-ist is ordered and mutao-le data stfucture
Dl 3.4 Tuples Data Type

i.M..-i,1;i!.1y,i*,**"u,*,,^ti,il^ii,,,,i,;..-
A tuple."or"r.r,r-u or.,oou.*n*;;;i;r";r**o or."**r, ,io
""i*.rr"""arr"*r. rn"." u"rr,
"r"
representation of tuple is very similar to iist representation. Tuples are expressed in following fbrmat.
tuple=(item 1,iiem2,......)

)s. 3.4.1 Creation of Tuple


- As in python we don'[ need to declare type of variable. We can creare a tuple by sirnply vrriting
tuple name
and assigning iterns of list in parenthesis. In the example, Fig. 3.4.1 tuple "t1 1,,.
consist of 4 items.

t3.3mf 3.r,2, S*4


pr"g*rqtrr)
(3r 3,3,4)
Fig.3.4.1 : Creationof Tuple

Similar to the list. tuple may include items oldifterent data types. The only major difference
between Iist anr3
tuple is, lists are mutable and tuple are immutable.

We cannot change the items of the tuple once it is declared. In tbllowing example
we tried to change element
of the tuple by assigning new value to it, however it raises the error, shown in Fig.3.4.2 as tuples are
"immutable".

-tIl*q1,i,3,i;

lI l l'; t.t

r1)i.,f i'!.ia-l^
Iracebeck fmost reeeflt ca
lL 1ast|

abject dses nst suppsxt iter* a*signment

I'ig. 3.4.2 :'Iuplesare immutable

Teeh-Neo Pulrlieations,".., ...... V/ierc Authors inspire innotation


...-4 S'ICEIN SIIAII Yeature
)a 3.4.2 Accessing Elements of the Tuple

Similarto the list data type we can access the tuple elements by their index, as shown in the Fig.
3.4.3.
-
- The 4e element in the tuple "t11 is "4", we can access it using its index. Tuple index start with '0' hence

index of the 46 element is 3.

{1, I, 3, {}

printi"the fsurtl: element j.n the tuple isi ", ttr1[3]1


the fourth element in the tuple i.ul 4

Fig.3.4.3 : Accessing tuple elements

We can access elements of tuple in loop statements as shown in Fig. 3.4.4 :

lftx{11*, Sr*}
pr'int i'?uB&e
,-.,.,",,,,,,,.., elefirsrtt; * rvdi';

Tupne *lementl tr

Yuplt *3effie*t: t
?up1* *3a**e,rtt: *
TupLt alement; 4

- ;.
1 11= ( u.$. 1-y'! *os t't,"i *r-.tt*a*. 1,.3**ts${?8:l}

rrirrt{"Yf&, Lity is i.n the tup3.s')


6i;;; i-,,''".':,"'--ft'.+,-+= t,',.,,,,,.,.,t'it,, :=1=
:

..';..., p;g;*'*.,'ffi,r$:.n,,,tuBt*, l, ll 1.:

Y*s" LilY is in tlie tuPtrt


Fig -3.4.4 z Accessing tuple elements usinC loop

)3. 3.4.3 Adding/Hemoving/Deleting Elements of the Tuple


..immutabld' hence We cannot add, remove or delete elements in the tuple. However we can
Tuples are
delete complete tuple using del0.
we can try to
We cannot add item in the tuple, here tuple t12 has 4 elements so on next index i.e' 4t index
add element by assignment operator. However it will raise error as shown in
Fig. 3.4'5, because tuples are
"immutable".

...,1 SACIIIN SIIAII Yentare


Tech-Neo Publi calions...........Vberc Authors inspire innovation
Typef*or lracEbatk {n*st rece*t eatrl ]est]
<ipython- i*put - 138 - in i,j:iii: iililri.:,i
$1bb7edk7a3l
i #You cennot add eleaertr in the tuple
; 11!x{' Li1}' r'Fa*e *.'0r^rhid*' r' }al*ilt*' }
"--l ! t1?{,iir'lslip5'
a prirt{tlt}

Typfror: 'tuple' object does not s$pFfi't iter essigrt*ent


Fig.3.4.5 : Adding element in the tuple : error!

In the Fig. 3.4'6 tuple "t12" deleted using del$ method, hence when we 6ry to print taple "tl2" it will raise
error, shown in Fig. 3.4.6 as tuple is already deleted.

Iracehck (nust rec*rt c*tl last]


{tpytho*-inpt-13S-***S*t53r$*r in iri,,r:4:j;,,: i
I 112a{'Li}}' ;'Er**' r'Sruhidi'.*, Ii*mine, }
: drl t12
----) I print{tl2i

Itlfli*Error: nrfl€ 'ilZ' is not defined

fig.3.4.6 : Deleting tuple elements


3.5 Basic Tuple Operations

The below operators are explained below with the help of example:

+ Concatenation
,.<
Repetition

tl Slice

[:] Range Slice

IN Membership

Tech-Neo Publi cations. -...-...Vhere A uthon iaspfie inaouation ... -4 SACIIIN SIIAII Yen t arc
Data Structures in

3.5.1 Concatenation
This operator helps us to concatenate
either sides of the operator. r1.{1r11?l , , ;

In the example, Fig. 3.5.1 there are


two tuples defined namely "t1" and :r#*+i'*fttffiid f_ i* lyrei i' +t]ffi,.,i1i",
"A". The concatenation oPerator
adds these two tuples and new tuple concstimtiffi 0f ffi tuplss ie t (1, I, 3r {, 5, 6r ?l
"t3" is created.
Fig.35.1 : Concatination of tuPles

b. 3.5.2 Repetition
The repetition operator creates multiple copies of the list. In example, Fig.3.5.2'11" is repeated for three
times using repetition operator.

:tlx1lr?rXr{}*}
iprist{u f&s r.ppitttion is to, tI}

{.& reltrtiffi tt r {lr 2, !, {, 1, l, N, {, ln l} Xr {}


Fig.35.2 : Repetition of tuple

)3. 3.5.3 Slice


jtItrl
t

This operation gives us character from given index. In example,


Fig. 3.5.3 we have accessirl the second element of the tuple "t1", with 2
its index i.e. l.
Fig.353 : Itrple slicing

b. 3.5.4 Range Slice


- This operation returns the characters from a specified range.

- In example, Fig. 3.5.4 range slice operation is performed. This operation uses the concept of haH open
interval. This means 1 is inclusive and 3 is exclusive. ( 1 and 3 are indices)

all[1:3]
Inclusive Exclusive

- It will access tuple elements from start i.e from 1o indexed item of list and will tlfLl3 ]
go up to 2d index item as this is half open interval (that means 3'd index item
will be excluded).
tt, 3)

Fig.3.5.4 : Iirple range slicing

Tech-Neo Publi aliors...... -... Wherc I a tbon inspirc ianouation ...A SACflN SIIAII Yentarc
E - 6th Sem. - Data Structures in

b. 3.5.5 Membership +al-,i "! n :t A E t


L4-\4r4rJaisJa Seffi*r'frli.a'.).
This operation is used to check whether that
particular element belongs to the tuple or not. b f-n El_
In example, Fig. 3.5.5 and 3.5.6 membership
operation is performed.
True
Fig. 3.5.5 : Tuple membership

If the element is present in the tuple then result will 't\,li.a ' in tI
be true otherwise false.
True

n
Anna '
False

Fig. 3.5.6 : Tirple membership

Dl 3.5 Built-in Methods of thc Tuples


As tuples are immutable there are only two built-in methods of the tuple.
'I

Meth Description

cOunt Return number of occurrences of item.

index Return index of first


occurrence of the element provided as
argument to the index function.

The demonstration of these functions is


given in Fig. 3.6.1 :
rl
( l, 2, 3, *, 1, 2. 3, tl, L, 2, 3, {}
tl.couati € i
3

:
tl.Lndax{3}
2

Fig, 3.6.1 : In built functions of tuple

Tech-Neo Publi eations...........Vhere Authors inspirc innovation ...J SACIIIN SIIAII Yeature
with
? Difference between Dale Structures in
list and tupte

List is ordered and mutable


dahsfucture.
Tuple is ordered and
immutable dak structure.
List is represented with
the square brackets
separated by commas. [] Tuple is represented
with the round brackets
separated by
()
commas.
Listl - [1,A,3,4]
Tl = (1,2,3,4)
: @ modified afrer creation.
lrpl"r cannot be changed
! List supports more builrin
rnethods.
Tuple supports less built_in
after creation.

methods.
5.
!t13t a variable length.
Tuple has fixed length.
*l 7.7 Sets
::t is co'ection of elements
but they are unordered.
Trrere are two types
of set:
\ 3.7.1 Creation of Set
Sets

- Set is unordered collection


of
unique data elements.

- The elementsof the seB are


unindexed and, immuahble,
f33r:{.x..,F.,,ft,1
pri.l}f. i gletl ;
1.**. *y,.. .;"),,.-,..,,...1
however set is mutable
data
structure. Set is collection
elements that can be
of
changed
fff*;l,I*l;;'.'ii '=rl
as per the requiremenl {'z'. .y., .x.}
In
other words set is mutable, sotl..adri{
as "td.l
shown in Fig. 3.7.1.
Pri3lt. i getl )
Duplicates will be removed l'Z* r ,ti., .yr, *,..l
i.e. set will be a collection
of l
similar data items without E. TF€ i EAEl
}
repedtion. :1,€lt,

Fig. 3.7.I : Set data type

feeh-Neo Publi

...-4 SACIIIVSTTLfr6;
You cannot use index for accessing the sets since sets are unordered elements.
You can use loops to access the elements. Demonstration is as shown inFig.3.7.2.

*S*
e3.t={:'An , 'E},' r 'C' , }
for count in s1L:
print { count }

B
C
D
A

Btg.l.7.2: Accessing set values

b. 3.7.3 Deleting Elements from Set


: We can delete items from set using pop o{ remove method. Demonsfration is as shown in Fig 3.f.3.

s11={,A','8",C','D'}
print { sXl }
$t ,pa*t() .. ,' . ",' i',,',,, ,' ,,",

:'r,,,
$rti.*t{,.$fl},','..,..1,r,,,,.'::,r,,',,'',

t
rB*, rc*, 'r*" rA*3
ttf*, *frt, tA'I
sll={ 'A' , 'B' , 'C , , '*, }
pr.i.nt{ sXl} :

,E t..i#g OVs{.1*..fr...-...},..t,. ,: .,
I tl

,,,,,,

pnirrrt { sXl}
.ri*.i.;,,,t:ir;i.:+i.ii:,,;,,,;,-i r,,,,,r..;..':,,iirj:..:tt:*r,i i.i!i:.t..i,,r::i.:::::..

{'Br, rC', nA*1


rD*,'Ar}
t*Bn, 'iln,
Fig. 3.7.3 : Deleting set elements

Tech-Neo Publicatione -......... Wherc Aarton inspfie iaaouation ...,1 SA CIIIN Slllt rc
Yen t a
- otn Sem. - Comp)

3,7.4 Adding Elements in Set


can updatetadd new values to set using add method/update method. Demonstration is
'-\-. as shown
' .+.

st={'A'r 'B', *C'r'ilt }


sl"add{'E'}
pnirrt { *1}

{'D,' , 'Ei' , '' E' , 'c' ,, 'A'}


s11={ nA', 'B' ,'C', '$'}
sll,update('E')
print {,s11}
d
*s,t, t En. 'sn, 'ct, 'A'3
Fig. 3.7.4 : UPdating set

3.7.5 Frozen Sets


These sets cannot be redefined once they are declared as frozenset.

Hence they are called as immutable sets' shown in Fig' 3'7'5'

Sr{nt { sst,X }

frouanretl{'b' r'c'r'a'}}
typa 1 set2 i

froE*nsat
Fig. 3.7.5 : Frozen set

....1 SACIIIN STAII Yentun


Tech-Neo Publi eatiorls.,........,Were Authon inspirc ianovation
with - 6tr Sem. -

Dl 3.8 Buit-in Set Methods


l:ir;t,rl:;rl;1:::.::il: r* ,:. ti*.,
1 add0 Add an element to a set.

2. ClearQ Remove all elements from this set.

3. copv0 Return a shallow copy of a set.

4. Difference0 Return the difference of two or more sets as a new set.

5. difference_update Remove all elements of another set from this set.

6. Discard0 Remove an element from a set if it is a member. If the element


is not a member, do nothing.

7. Intersection0 Return the intersection of two sets as a new set. (i.e. all
elements that are in both sets.)

8. intersection_updateQ Update a set with the intersection of itself and another.

9. IsdisjointQ Return True if two sets have a null intersection.

10. Issubset0 Report whether another set contains this set.

11. Issuperset0 Report whether this set contains another set.

12. Pop0 Remove and return an arbitrary set element. Raises KeyError if
the set is empty.

13. Remove0 Remove an element from a set; it must be a member. If the


dlement is not a member, raise a KeyError.

14. symmetric_difference0 Return the symmetric difference of two sets as a new set.(i.e. all
elements that are in exactly one of the sets.)

15. symmetric_difference_update() Update a set with the symmetric difference of itself and another.

16. UnionQ Return the union of sets as a new set. (i.e. all elements that are
in either set.)

17. Update0 Update a set with the union of inelf and others.

)a 3.8.1 Basic Set Operations


Set has four basic operations which are enlisted as follows:

1. Union 2. Intersection 3. Difference -1. Subset

Teeh-Neo Publi eationa... -.-.- Werc Autlon inspire iadoua tion ... -1 SA CIIIN SilAII Yen t u rc
El ,ronr"*ming with Python (MSBTE - 6th Sem. - Comp) 3-18 Data Structures in Python

1. Union : It is defined as set of all the elements present from all the sets.

A-{1,2}
B = (2,3,41
C={5}
Then,

AUB =BUA =t 1,2,3,41

AUC = CUA ={1,2,5}

BUC = CUB ={2,3,4,51

AUBUC = 11,2,3,_1.51

2. Intersection : It is defined as the set of common elements present in the set.

A= {1, 2,3,4}
B = 12,3, 4, g|

C=12,4,910]
Then,

AnB = BOA =12,3,41


AflC = CnA ={2,4}
BOC = QflB ={2,4,9}
AnBnc = {2,41
3. Difference : If A and B are two sets then difference between A and B are defined as elements which are
only present in A but not in B.

If A= {1,2,3,41
B= {2,3,9}
Then,

A_B={1,4}
B-A={9}
4. Subset : If A and B are two sets given then set A is called subset of B when all elements of A are
present in B.

If A= U,2,3,4|
B = {2,3}

Then we can say that, B E A that is B is subset of A.


Teeh-Neo Publi cations...........Werc Authors iaspirc innow tioa ....4 SACIIIN SIIAII Yenture
E--q
l.hl ptogr"rming with Python (MSBTE - 6th Sem. - Comp) 3-19 Data Structures in pvthm

Demonstration of these four operation are as follows :


-

*s€ft.a@4.3n3..3,4i

t.3n$*m r eetJ" ,;)


I

sst

gratlm,,SrSrSrSr?i.

#s93. * r*Nll*{:xfi i #{stg i


t1, 2c 3,r &." sr 6, :lb

aet tr * s.lntelrsecticrm r. sett ,i

t3, 4i
grgtS * *ii-f feref,irgs l. strtZ i

{4" 2}
aefr3. . add. i 'S ,i

:e4*
dH L*
1

{r, 2c 3r, *r *}
setf. - iesrebeet , eet2 i

FaLee
Dl 3.9 Dictionary

Dictionaries are defined in terms of key-value pairs. Usually keys are defined in terms of strings/numbers.
But values can be of any type. Dictionaries use curly braces. Dictionaries are mutable.
That means you can update the items of dictionary as and when needed. Let us understand use of dictionary
in real life, it can be used for data storage - in dataset we need to remember column name at various indexes
to access the elements of the datasets so instead of remembering that a student's name is at list index 0, and
the address is at list index 1 - we can create a dictionary with keys of 'name' and 'address' by this way our
code will be more readable. We can also use a dictionary to easily count the content of a list.
Tech-Neo Publieations...........Vhere Authors inspire innouation -..,4 SA CIIIN SEAII Yen tuv
(MSBTE - 6tn Sem. -
Data Structures in
Dictionaries are always expressed in following format
:

Dict = { keytr :va Lue 1,keyZ :vatuez,...............}


Keys and values in dictionary are divided by colon (
: ) and these pairs are again separated by commas(
, ).
while defining keys you will have to remember that, these
keys should be unique. Because these keys are
going to provide an access to dictionary elements.
You can update items, delete items etc using keys.'Keys
defined in dictionary are immutable.

?a

E*pty dictionary can be created as shown in Fig. 3.9.1 and3.9.2

ldie.tg{f,,;"'f"'1;
print{dicti}
pnint{type{dictr}
.,... }

dcLass'dict'>
Fig. 3.9.1 : Creating dictionary

Now, let us create a dictionary with some elements


in it.

dictZ={ 'ner$e ' , ,Bob i


Age' :11,
r&larks'IfiS.#1
print{dict2}
;l:.=.,",;i:i;t:is::;:.:.i.:i",:ri;.+r,.;:,.,+;.i,.*-.,.,,,_:!.!r:i!.ii:::i.ri+::.L,1in.:;iit:i.i;i{
.....'.-....,,........,....'....--..-

{'name': 'Bob*, ,Age,


21" '$4frrks *
: gg. Bl
FiS, 3.9 2 : Creating Dictionary

The dictionary is named as .dict2,.


The first element of dictionary is 'name' : ,Bob,
where ,name,is key and ,Bob,is the value.
The second element of dictionary is'Age' : 2r
where'Age'is key and 21 is the value.
The third element of dictionary is 'Marks' : 88.0
where'Marks'is key and gg.0 is the value.
From above example we can see that keys and values
have data types such as string, integers. and floating
point numbers' The important point to remember
is that every key must be unique and once keys are
defined
you cannot change it.

Tech-Neo Publi cations........... yhere A orhrn irrpio io, ou o:*


...-4 SACI{IN SIIAII Yentare
ing with (MSBTE - 6th Sem. - Data Structures in

b. 3.9.2 Accessing Elements of A Dictionary

- There are two ways two access a values from the dictionary, as is shown in Fig. 3.9.3.

l. You can directly use the key to get access to the value.
2. You can use get$ method to get access to the value.

g1t:{ 'nai*E' : ' Eobl ,


'Age:' : f 1.,
'Flarks'i$6.#i
print{'The value of nrffie is;'rdict2l'name'j}
print{'The vaLue *f age isl'rdictl.get{,Age, }}
e velue of fiattle is: Boh
value of age is: 21

Fig. 3.9.3 : Accessing Dictionary element

If key is not available in the dictionary then error will be generated, as is shown in Fig. 3.9.4.

61]={'nanre' : 'Bob',
'Age' :2i.,
&arKs":x6.81
rilt('Ihe vrlue of n*me is:'rdicil['lrlumber'])

Traceback (most recent cal] last


ipyt*an -input-54- 3181di4*5fu 68r in i i i+ij ri j'.i:

3 'Age'1}l,
) '!,!arks ' ;88.9]
----r 4 print{'The value cf na*e is:',dict2l'Sumber,]i

:'tlumber'

Fis3.9"4

b. 3.9.3 Adding Elements in the Dictionary

As mentioned earlier dictionaries are mutable. Hence we can perform various operations on the dictionaries
like adding new pair, deleting a pair.

- The new element can be added to dictionary as shown in Fig. 3.9.5.

Teeh-Neo Publieations..... ...... Vkere Authors inspire innovation ...-1 SltIIll SHII| Yenture
dict2={ 'na$e' : 'Bob' ,
t
Aoot 'J';

'liarks':88.*]
rlnt{'The contents cf dictionery ane:,rdict2)
ict2[' (ity' ]=' London'
print{'l4odified contents of dictionary are;\n'rdict2)

Fig.3.9.5 : Adding elements in Dictionary

?3. 3.9.4 Removeldelete an Element of Dictionary

There are two ways two remove an element from the dictionary,
shown in Fig. 3.9.6:
1' You can use pop0 method. The method takes key as an argument. Hence
when thd function is called the key
mentioned in the argument and its value gets removed from a dictionary.

2. You can also use popitem$ method for the same.


3. You can also use del keyword in order to remove specific element or
complete dictionary.

d1={'a' : l,
lhr.1
v . i,
I tl
L '2
. JJ
I At ..+,
u n

'e' : 3)
print{' Dici.nany :, rd1)
d1. pop( 'c' )
pri.nt{'After pop:' rd1}
d1. popitem( )
print{'After popitem operation:' rd1}
del(d1[ 'b'] )
print('After de3.:' rd1)

er popitem operation: {.a,: 1, ,b,: 2, .d,: 4}


er del: {'a': 1, 'd': 4}

Fig.3.9.6 : Deleting elements of dictionary

Tech-Neo Publi cations........... Were Authors inspire innova tion


... A SA CIIIIY SIIAE Yea t a re
H Programming with Python (MSBTE - 6th Sem. - C Data Structures in

7.lO Python Dictionary Methods


Dl 3.1O

;-@- , ;;r;;;1;:,;:;i'^* ;:!!-i:;,** ii*il:.,.--.---.-,..,---.-..-,-.r.....-.,..,--. a;;*.i


The dictionary methods supported by python are enlisted as follows :

Method lYame
clear0 Function removes all elements from dictionmies.

copy0 Function returns the copy of the dictionary.


get(key) Function returns the value of the key specified in argument.
item0 Function returns all the contents of dictionary.

keys0 Function returns all the keys of dictionary.


pop(key) Function removes value for key specified in argument.
popitem0 Function removes an element.

setdefault(key) Function retums the value of key specified in argument.

update0 Function is used to update dictionary values.

values0 Function returns all the values of dictionary.

Demonstration of dictionary methods is shown in Fig. 3.10.1.

' t'. t-',tt,A#':'3,31, t,,,


t''',..'-, t'""'
,,tt-t'=',,, ,

pr:int( r i1'diet@y conimts, in 1, airiir;iti*i{,} i"."..,..,.-


piint('AlJ. keys fronr i dictienary:\n ',dicie.keys{)}
print{,,14}i: ,veluei,:rfiors,,,a'diitio*iir::tn,,.:i,;aiitii+q sC}.l

All dictionary contents:


dict_items{[{'name','Bob*}, t'Age', 21}, {'}larks', BS.A)J)
All keys from a dictionary:
dict_keys{['neme'r'Age'r'illarks' ])
All values from a dictionary:
dict_values(['8ob', 21, BB.0]]
dictZ={ 'name' : 'Bob' ,
'Age' : ?a ,
'mirks':BB-8] --
M=dict2 . Eetdef ault ( t4arks ' )
pr5-nt('Harks:'rH)
Marks: ,8S-8

Teeh-Neo Publi cations......-... Wkere Aatlors insphe innovation ...,1 SACIIIN SIIAII Yennre
dict2={ 'nane' : 'Bob' ,
'Age':21,
'$4arks':$8,8)
dict3=i 'RollNumber' I 1$1)
dict2. update{dict3)
pri.nt{'}iodified dictionary : \n', dictS}

Hodified dictionary:
{'name': 'Bob', 'Age': 21, 'llarks': 88.0,
'Ro11l{umber': 101}

dict2={ 'naltu' : 'Bob' ,


'Age':21,
'Marks':$8.0)
dict3=dictz. copy( )
print(' Ner,u dictionf,ryl \n' rdict3)

New dictionany:
{'name': 'Bob', 'Age': 21, 'Marks': 88'0}

dict!={'neffi' : 'Bob',
'Age':21,
'llarks ' :88,0)
print('Dictianary contains:' rdict2)
dict2.ctear0
print('Dictionary contains:' rdict2i

0ictionary contains: {'name'l 'Bob', 'Age': 21, 'Flarks': 88.&}


0ictionary contains: {}

Fig.3.10.1 : Dictionary methods

Dl 3.1I Built-in Methods for Dictionary

List of buitt-in methods for dictionary are enlisted as follows, in table and demonstration is shown in
Fig.3.11.1.

A athors inspirc innova t io n ...,1 SACIIIN SIIilI Yea t u re


Tech-Neo Publi a1iots........... Wherc
lVlethod name Description

1en0 It returns the length of the dictionary i.e. number of items dictionary consist of.

sorted0 It returns keys of dictionary, it sort keys.

all0 It return True if all iterable elements of the dictionary are True, If not, anyQ
returns False.

anv0 It return True if anyone iterable element of the dictionay is true, If not, any0
returns False.

diit+=it:'ar,3t'L';3:'i*,a:'d'r4i'g,,],'',
print('0riginal dictionary elements ;',dict4)
iil' i1e,n {dieta}}
pr,i*t{,' Length of ,,,6iq#rn*ry
print{'sorted functionr',sorted(dict4)}
prunt i ail(dicta) i
print(any(dict4) )

iginal dictionany elements: {1: 'a', 3t 'b', 5: 'c', 2: 'd'r 4: 'e'}


ength of dictionary is: 5
Sorted function: [1, 2, 3, 4, 5]
rue
F' IA

Fig. 3.11.1 : Built-in dictionary functions

,trl,El
Dictionary is rnutable data structured
Doesn't follow any specific order

Q. 1 What are different data types of python?


Q. 2 What is difference between list and tuple?
Q. 3 Write a short note on dictionary.
Q. 4 Enlist any 5 built-in methods for list data type.
Q. 5 Justity'Tuples are immutable'.
Q. 6 Explain basic set operations with example.
Q. 7 Explain how to access set elements with example.
Q. I Define frozen sets with example.

Chapter Ends...

otlu

You might also like