Professional Documents
Culture Documents
Chapter III
Chapter III
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
Go.3.4.1WhatiSthediffereneebetweenlistsandtuples?(4.Marks)
3.4,3Adding/Removing/DeletingElementsoftheTuple''
with
3-2 Data Structures in
____-_-__.......'.....:____
| .,. ' :
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:
- 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.
i.;*a*i listf )
- r e-*
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.
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
'1.:E+l
--t
0perators Descrlption
+ Concatenation
Repetition
tl Slice
1n Membership
1J-rr'1,1
IT5 Ld,," II5 ^rr
tD
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
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[&
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
If the element is present in the list then result will be true otherwise l'alse.
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
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']
,,
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,......)
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|
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
{1, I, 3, {}
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}
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.
The below operators are explained below with the help of example:
+ Concatenation
,.<
Repetition
tl 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 , , ;
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}
- 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)
Tech-Neo Publi aliors...... -... Wherc I a tbon inspirc ianouation ...A SACflN SIIAII Yentarc
E - 6th Sem. - Data Structures in
If the element is present in the tuple then result will 't\,li.a ' in tI
be true otherwise false.
True
n
Anna '
False
Meth Description
:
tl.Lndax{3}
2
Tech-Neo Publi eations...........Vhere Authors inspirc innovation ...J SACIIIN SIIAII Yeature
with
? Difference between Dale Structures in
list and tupte
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
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
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.:::::..
Tech-Neo Publicatione -......... Wherc Aarton inspfie iaaouation ...,1 SA CIIIN Slllt rc
Yen t a
- otn Sem. - Comp)
Sr{nt { sst,X }
frouanretl{'b' r'c'r'a'}}
typa 1 set2 i
froE*nsat
Fig. 3.7.5 : Frozen set
7. Intersection0 Return the intersection of two sets as a new set. (i.e. all
elements that are in both sets.)
12. Pop0 Remove and return an arbitrary set element. Raises KeyError if
the set is empty.
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.
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,
AUBUC = 11,2,3,_1.51
A= {1, 2,3,4}
B = 12,3, 4, g|
C=12,4,910]
Then,
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}
*s€ft.a@4.3n3..3,4i
sst
gratlm,,SrSrSrSr?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
:
?a
ldie.tg{f,,;"'f"'1;
print{dicti}
pnint{type{dictr}
.,... }
dcLass'dict'>
Fig. 3.9.1 : Creating 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.
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'])
3 'Age'1}l,
) '!,!arks ' ;88.9]
----r 4 print{'The value cf na*e is:',dict2l'Sumber,]i
:'tlumber'
Fis3.9"4
As mentioned earlier dictionaries are mutable. Hence we can perform various operations on the dictionaries
like adding new pair, deleting a pair.
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)
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.
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)
Method lYame
clear0 Function removes all elements from dictionmies.
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}
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
List of buitt-in methods for dictionary are enlisted as follows, in table and demonstration is shown in
Fig.3.11.1.
1en0 It returns the length of the dictionary i.e. number of items dictionary consist of.
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) )
,trl,El
Dictionary is rnutable data structured
Doesn't follow any specific order
Chapter Ends...
otlu