List
List
LJ STS
. ,A ND.
fUPLES
A
. 11 1
sequenc e 1s to s tore ond pr OCC'ijt3 0 1111 ,u >K oupnft•lt1w 111 , ' , 11w pu1 poar of
111 y
. \ I O 1 (' 1i' lllt· t1t tt 1 I p .. I
t uples ond d1c t1onnnc s ore vc•ry itl'lt-\ort, ,
1 n, :we 1tH·nt ('
' _y l 1 11 11 , st r111Kn,
l1Ms ,
,, I11 111 1
ome common opcrotio ns like indt•xin, , on,I 1. < YP ' ' J\11 s1·q,,,,,,. rs
1
a.}loW S . !"I " g 1 r 1nR. In t II,~ et 111 •
abOUt lists, tuples and their operatio ns in Python . · P 1< 1 , y1111 will Ir ,rn
. US1
~ A list is similar to an array that consists of a group of cl,' m , l ..
. I . '" e n 8 0 1 llt'rn 'I , ,Jt1 '1I l1kr 1111
array ,
a list can store e ements. But, there 1s one maJ·or diffi"
st. crrncc lJ<•twt•t·n nn t 11 rny und
a li An array can store only one type of element s whcreo s a. - C(\n .
. " 11 .5 1 ~ 1ore CI 1 11 Cll'lll
tunes
•Jr-
of element s . Hence lists are more versatile and useful tho,, " n n r ny
are the most used datatyp e in Pythonprogram .,, " I Pt•t h.,p~ lists
s. ·
In our daily life, we do not have element s of the same type . Por exumplc, wt• tok,, mnrk'i
of a student in 5 subjects :
50, 55, 62, 74, 66
These are all belongin g to the same type, i.e . intege r type. Hence, we can rep, <' ~l' l\l such
elements as an array. But, we need other informa tion a bout the s tud ent , likt• his wit
number, name, gender along with his marks. So, the informa tion looks like this .
10, venu gopal, M, 50, 55, 62, 74, 66
Here, we have differen t types of data. Roll number (10) is a n integer. Nnme ('V<'nll gop,ll)
is a string. Gender ('M') is a charact er and the marks (50 , 55, 62, 74, 66) n r e ,.t~,\11\
integers. In daily life, generall y we have this type of informa tion t hnt is to bl· s tored nnd
processed . This type of informa tion cannot be s tored in a n a rray bC'cause nn t111 O\ e,111
store only one type of element s. In this case, we need lo go for lis t dnlntype . A lis t co n
204 ( tit tli' t1Hl 111
f ,,
1 11
rlw 9 1t1rl1111 111 111for1rir,t lt
,r, ell
t ,1,ffrff "'
1119ttJP('C
ill (\ I' •p.1'. ',0, Pi ', I l,i' t r,t I 1,f, I
("!lfl r,r111n l\ nt ff f10, t v~MIJ uni>•'( l)llI
•,. t 11d1•1!1 ' fl ll l I ll I ' '1 11111 (I II! •
1,tuu11l!
1 th'' Ii 1111 •11f1t oy ,1 , ,,,,rn l,y 11 1111p1Y w, 11111v, ,. 111 11 ,y,
'Pflir r t•r •r('
1
1 1 111 1
ol> <1'" 11111 h•I wit h 0111 1' 11
l'l"" ' ' "" r I ' II I
r•" ,..,., 1st" 11 ,•11•I]pl V ,
t• etnP I y I I s t
c,.
thl • ,,n
I . Jdl11V t '"' ,-l,•m 1•,11 n ,11 R1tl1· , , ' I
" '• ,, .,
i,
I I by 1·111 ,,, , p1111 I
• ,. 11 lff • n r fd<'d by 11 < 0 11111111 ( , ) T<1 VH·wI 'H j11t11
I hi' 11• 1 n 111rlC' Ill II ,r• I'' ;n I I) I llll< I""' 111I 11' r•I,.,.,,,,11, ~
I hr
'Ill"' "r
r./111 , I I 111 I ilcl t,r 1-11 P
I i,r li• I • int
, '
:n,,. r1,•n" 111' " I • ,111 , 1rnpl YP''"" '·
• whnl• ' WI I ' ' '•I
11111 till ) •
i nt (st ud"nt
pr !½ f(ivr 11 b<'Jow :
rt,r.li•'''ppi•n• ••· , ·~•, SO, 55, 62, 74, 66J
[ , •vrnu gopa 1 ' · ) ore com rnon ly done on
10nnd slir ing op"rnt10~ ~ num lisl H. l ndexin
bers in the lis t. Thc pmii lion numb R rcpre,~
,
,dt•' "g
no "c)rrncnt fi by thc1,
·r pos1t1on
0
v
/i
nrcrs
'
Oon"'
s1 ,.,
ord, 11 ore wri ·ucn ,ns1 cs ud en t[ J]
rcpr escn 1, 1
ts • c emc n t and ,
er, st n1,
'd c1uorc braces as: stud ent[O], s tud ent[ I I, etc
0... It
art fru
tr\ "'••n
90 ts O'" clcmcn 1, 51 .
drn t!OI rl'pr<'scn ' omc wc can wntc: forth •
' '" . the stud ent • n ' . ,,·
e,carnple, to pnn 1 ,
Print( stud ent[ l]) ·ven below:
f studen t appears as gJ
The name o
venu gopa1 . a piece of the list by men tion ing starting anct
Slicing represe nts extra cting - . [
-
rnbers T)ie gener aJ format of slicing ,s:d 'sta..:!:....'top: stepsizej. B enct·'"!
. . ' 'Jl
position nu · . b the last element an steps 1ze w1 be 1. ForY defa,,,4lt,
•,tart ' "''
·11 b O ~
'stop 11
' w1 . . e of the list cont
·- ainin
- g O'" to 2"' elem ents . - exam I
Pe
student!0:3: Ll represents a piece - ~
;;;nt(student[O:~:l])
The elements are given below:
[10, 'venu g_opa l ' , 'M' J .
We can also write the above statement as:
print(student[:3:])
The same elements appears as shown following:
[10, 'Venu gopa l', 'M']
Here, since we did not mention the start ing elem ent
posi tion , it will start at o and
stepsize will be taken as 1. Suppose, we do not men tion
anyt hing in slicing, then the total
list will be extracted as:
print(student[: :])
l.i~ts And I u 111 c
·~ th<.' (1tttp ut ns:
•~r,l:\, ~ I
c.._amPI«'
range(4, 9, 2) ·11 generate nurnbcrs from 4111 to 8'h in steps f .
. statement w1 o 2, ' e !
The prcccdJJ1g . d s not re turn list of nu m bers. It rctur 'I, f>, ll
function oe , d , · , ns Only 11 ·
, th" range () b ut 's tart', 'stop an step s1ze. For examp[ . ra "
Jn ,ot , the data a O e, if we ~p ti
1
object tMf stores 2)) ,.,,,,.. •~
ri nt ( range(4,9 , . .
P nt will display.
fhc prcced111· g staterne h. s is the obJ· ect g1· ven by range()
range (4 , 9 ' 2) # t sed
1 in for loop to get the range of numbers d .
. object should be u es,rect b
rtus range For ""ample: Yt;,
progranuner. . ·
. ,·n range(4,9,2), ✓
for , print(,) . .
. display 4 6, 8. Hence, we say range obJect is 'it
statement WI11 1
t h"
fu tions and loops that expec somet mg from wh .
erab1 '
e, th
The prece ng d . tch th <It
di target for nc b
is suitable as a F ample range object can e use m for loops t ct· ey r_,,_
' . ·rems. or ex , . . o is I -'<11
obtain 5Uccess1ve I . fu ti n to create a Itst. In the following example th pay 1h
or with list() nc o . . ' er e
numbers: . h rst(I function to create a hst. "'!e-0
function is used in t e J
1st= 1ist(range(4, 9, 2))
pri nt(1 st)
The list is shown below:
[4, 6, 8]. h 1" t() function and using range() alone to create a list the
If we are not usmg t e b"
isect returned by the range() function . For example, ' n we ""
"ijl
have only range c1ass o ~
1st= range(4, 9, 2)
print(1st)
The preceding statements will give the following output:
range(4, 9 "2) # this is not a list, it is range object
1
In this case, using a loop like for or while is necessary to view the elements of the list. For
example,
for i in 1st:
print (i)
will display 4, 6, 8. In Program 2, we are showing examples of how to create lists using
the range() function. In this program, we are not using the list() function .
~
p,7, 2: A Python program to create lists using range() function.
## creat, ng 11 sts using ran~e() function
create a 11st with o to consecutive
. integer
. numbers
l''fl t OiH
.~-1 ',. •-ttJ.w di~Jll ~ ~t
J. , .... '"" , ,
fl t ll '
' '
• '
t'lnlt •• nt by ~l ""
-.:
pr • t:hr ow cursot lo nc ~t line:
nt('
~;, ,i~t with i ntegers from s to
-,,rf!Jltf! rangc(S, JO) 9
•~· tl ll!I 1 ~t2 :
1i ~ ; \'f n ~ • • • end-' , )
fOf pf11 nt ( l • ' e
r~ nt 0
P a li<.t with odd number s from
I ,reaterangeis. 10. 2) # step size is5 to 9
· t3 :: · t3 · 2
1, s . l n l 1 ~ ' . ' end= ' ')
for ~ri nt (1 , • '
0-~;1,a, 9 ,
S , 9 ,
5 7 '
' hile loop or for loop to access element f -~ ~
s rom a hst h I
sew =-----=-=~::--~ -
, ca.11 u )<now the- number of elements in the list F · $ Caj} fun ctlon ,~
v.c -:----;-:--:- - • or exarnpl (I'
tvl to ents in the list. The folfowingwniJe Toot> t . e, 1en 1st) Five~ toti•I
of the I'is t ·. -
oufl'l ber ofntelem
us< re neves stn n in g from o·• tn the
1.as
telerne- - -
i=O "<len(list):
while rint(list[i]) # repeat from O_to length of list
p . 1
i ::1 +_
- 1 n'listl function in the while condition as· while · .
e the e ~ . . · t < 1en 111st). This w u ·t
observ ber of elements m the list. If the total number ~f · . 1 re urn
the to ta1 n u ~ - - ~ . . - - .
.11 become: while(1<n)._It means 1 values are chanaing fr e1ements 1s 'n ' ' then the
conw.i;tion WI
. lay all elements - of the list from O -to n-1
----,-_ - t:,• om O to n - l · Thus th i!'·I
I00pwi.ll d1sp _ _ _ _ :
other way to display elements of a - list is by- - a for loop ' as·.
using
(. ) - . # repeat for all elements
M f or 1· in list: -
- print 1 , ·
'i ' will assume one element at a time from the list \and hence if we display , al
Here, . 1 v ue, 1t
will display the ele~ents on_e by one. In Program 3, we are showing how to access the
-----
element s Of a list usmg a while loop and a for loop.
. . .
Program 3: A Python program to access list elements using loops .
#_displaying list elements using while and for loops
list = [10,20,30,40,50]
print('using while loop')
i=O
while i<len(list): # repeat from Oto length of list
pri nt(l i st [i])
i=i+l
2.08
·
= ·-
pr-in~(Ts1:) _ a n d range ()
Th e preceding s t s t c rn e n.t s wi JJ g:ive th e f"oJk:>vving outp-u.t:
(1, 2, 3 , 4 ]
N o vv , co n s id er 1.hc f"o JJ owin g statements:
1s1:.app e nd ( 9 ) # a ppend a new e l e men t to 1 st
p r-I n t:(1 s t )
The pr~c_eding stat<!rn e n ts wi JJ give the ·f "ollowi=g ou.tpu.t:
(1 . 2 , 3 , 4, 9 ]
e l emen.t in. the 1.ist._
- This can be
Updating a n e l <: m e nt m ean s changing t h e v aJue o:f t h e
done by ac~essrng the s pec ific e l e ment using in.dexi:n.
ox:: :slicin.g a.r:i.d assigning a new
vaJue . Co_n s 1d e r th e following s tatem e n ts:· g
s~ [1](- 8 # upd a t e 1,n: e l e m e n t 0 .c: 1 5 -
1pr,
n t: 1 st:) • .._
The pre ceding s t a t e m e nt s will gi v e:
[1, 8 , 3, 4, 9 ]
I r,,\1{'\\\ lnH f,l\Oh.'11'CIH s .
dr:f t,ir :u .11
t:t"''!' t1.l .. '3l • 10. 11 lur,chHe
,r
11-i~t(l st)
.:a · \ ii ~,nt t•mC"nt~ will
. gl\ll ':
l
11
' and i~
el~m ents of 1st
i't:\~ o l I r.
r1,c l''{l , 10 , 11, 4, 9) .
. g l\n
ekm <"nl from the hs t cu 11 be
1)t.1t,t 1tt
1
o~it ton num hcr o f t he cle men t toc one
b
t,~,
kf:~ tht' p # d 1
' ng '<lei' stnt cin" •
tll 1 1st [l] c d e lete d nt. The clcl ,tate mt> nt
e ete 1 s t el ement f
rr~ nt( lst) - rom 1st
. t app ears as:
the 1is
~c,1,"• [l, 11 , 4 , 9]
also dele te an
e lem en t u s ing th e r emo veQ
wee.sscan
the e1e
rnen t to b e d e leted . - - ~ ~ - ln th is m th
P e od. ~hould
1~ t ~ ( l l )
W('
# del ete 11 from lst
p --- --- -
list app ears a s :
~o~ , the
[l, 4, 9]
·tea pro gram to retr ieve the elements of
a li t .
Let's. Wf1
b usin g the reve rse () meth od, as: s m reve rse ord
easilY Y....:::::~~ - - - - - - -- - er:.. Thisca n be done
list . rev ers e()
_..:
11 reve rse the ord er of elem ents in the list
"""is wiu and th
11
i·st Sup pos e, we do not h ave the reve rse( e reve
) m etho d th rsed elem ents are avai.lable
"
;., the 1 ·
... . lay the elem ents in reve rse ord er? Thi
s can b e done, en how can we d
.
to diSP
men ts in reve rse ord er. For exa mpl e, let's
. .
usmg__while loop and eve1op 1ogic
the ele assu me " i : . a ·
· . - cces smg
·t1·ons of thes e elem ents can be specifie . . :.,_R,_. L,l_st-Yli lli 5 elem
d usm g indexing as· list[Q\l t . ents . The
pOsl
in reV erse orde r, we sho uld follo w the ord er: list[ 4] to list[O ' ·· · ~ o 11st[4} To disp la
to disp lay the
. . _ _.:......,:__ ] · The foll .
_ owm . e~
g w hil Y
hst 1n reve rse ord er: - loop can
~u~d - - - -
- -
while i~=O: . #. i rep re~ ~ts ini ~ia lly ...i-
prin 1J_ l1st [1])__! d1splay_f~om 4th to Qth
i:=1 # 9ec r~a se th, pos itio n eve ry tim elements
e.
In the prev ious co~ e, 'i' st~.J> wit~ .§l val'
-!_e 'n- ~• whe re !1' repr ~~en ts the num_b er
elements of the list. Thu ~ f the hs_!_has of
5 elem e~ ts , i wou ld star t from 4 th element
onwards till ~ th ele~ ent . _
Another way to acc ess elem e_nts in reve rse
o.rde r is by usin g n egat ive indexi_:1g . Whe n
write list[- 1], it repr ese~ ts tht last elem_!:!lt. we
Lis! l:.~ repr<::s ents ~ct elem ent from the end
Hence, -;_,e sho uld_ disp lay from _Jis t[-11 .
to list[-5}_so that the list will be displaye
reverse orde r. d in
1 ,v, [1
su11dJY ,
, '
'1
"' ~''a ,
1J •
d eversc order : )
printC'\nJ)n r # i wl11 be 4 lD 0th rlrmnnt ~ 1
j
.. 1en(d,1YS I
while
1 i> O: [')) # dbPlaY from 4th D
print(days 1 ·
; -. J
, verse order: ')
; .. -1 ~ days[-(d
print( \nm re ] re resents last e lcmcnt
1ars) ~ # di splaY from -1th to - 5th e]Pmr•nt,
whi le ,,.-l en . · '
print(daY•~ l , , t
i -==l
output:
c:\>python lists;PY
rn reverse order.
Thursday
wednesdaY
Tuesday
Monday
sunday
rn reverse order:
Thursday
wednesday
Tuesday
Monday
sunday
X = [10,20,30,40,50]
y = [100,110,120]
print(x+y) # concatenate x and y
✓
The concatenated list appears:
[10, 20, 30, 40, 50, 100, 110, 120]
Lists And Tup lr I 29 l
~ o f Lists
oeP
I' t
rep cn the cle me nts ot ll hst 'n ' numi... .
----
~c co11 , •JC t of tnn
\ -rite Y. •o • the list 'x w111 be iep cat cd for n 1· .
cs u~1ng .,., ope rato r
,,r. ,, . tC,<*2) # rep eat t he l; st >< f mcs as• 1
- For exa mp le, lf
prin .
or 2 tim es
)i~t app ear s as:
~o"'• ttlC 20 30, 40 , 50, 10, 20, 30, 40
[10 , ' - , 50]
rshiP in Lists ~
~e rnbe .1 ( ~ 1.. _ ,
r••
~,.., cheC
k if an ele me nt is a me mb er of a list J.J. A ~ ~
we c~·
1ernen t is a me b f h .
m er o t e list , the n 'in '
0
r not by usi ng .. ' d '
If tbe e . ot in the list , the n 'no t _ ope rato r retu ~nT an - not m ' opc ruto r
elernent is n in' ope rato r retu T ~ rue else Fn1se lf the·
- - ms rue else Fal se. See the e;a mp les
bC1ow: >< == .[1 0' 20' 10 '40 ' 50]
a: - 20 . # c hec k 'f
prf t(a in x)
n _ _ . , a is mem
. . ber of><
din g sta tem ent s wil l give:
'ft,e pre ce , ~ - ...
rrue
1fyou ,write,
· pri n~( a not in x) JI check if a is not a member of x
crive
_..:11
'fhen, it w:UA z:,·
fal se
To ~Vl·de a new nam e to this list , we can sim ply use ass ign me nt ope rato r
as·
y = X .
In this cas e, we are hav ing onl y one
list of ele me nts ht:1t wit h two differen
'y'. Here, 'x' is the orig in8 ; ri~ e t nam es 'x' and
and 'y' i~ the , alia s n~ e for the sam
modifications don e to 'x wil l als e list . Hence, any
o mo dify 'y a nd vice ver sa. Obs
state men ts wh ere an ele me nt x[l] erv e the following
is mo difi ed wit h a n ew v~u e. Thi
s is s how n in
Figure 10 .1.
X = [10 ,20 ,30 ,40 ,50 ]
y = x #x is ali ase as y
pri nt( x) wil l dis pla dy [10 ,20 ,30 ,40 ,50 ]
pri nt( y) wil l dis pla y [10 ,20 ,30 ,40 ,50 ]
29 2 Ch ap ter l 0
99 mo dif y 1 ~l ele me nt in x OJ
#
) (X) wi ll di sp la y (1 0,9 9,3 0,4 0,S
x~tnt (1 0, 99 ,3 0, 40 ,5 0]
~r in t(y ) wi ll di sp la y
: ~/ 10 I I I
20 •o
Be for e mo dif ica tio n
40
: ~/ 10 I I I
99 30 40
# x is c 1 on ed as y
y = x (: J .
e el em en ts 18
a lis
. t lik e thi s, a. se pa ra te co py of all th . O
W he n we clo ne .sto red Ult
md ep en de nt
. bs ts. He nc e, an y mo dif ica tions to ':x' affect }'. 'l'l'f'.e
lis ts 'x' an d 'y' are
. Will no t
vic e ve rsa . Co ns ide r the fol
low ing sta tem en ts:
)" ~ ·
X = (1 0, 20 , 30 , 40 , 50 )
# x is clo ne d as y
y = x[ :J la y (1 0, 20 ,3 0, 40 OJ SO)
pr in t(x ) wi ll di sp 0,2 0,3 0,4 0,S
pr in t(y ) wi ll di sp la y [1
# mo dif y 1 ele
st me nt in x
x[ l) = 99 la y (1 0, 99 ,3 0, 40 SO]
pr in t(x ) wi ll di sp 0, 20 ,3 0, 40 ,5 0]
pr in t(y ) wi ll di sp la y [1
X ---110 I I 20 30 14 0 I I50
y ---. I I1• / 20 30 14 0 I l
50
x ---. I I I I I I
10 99 30 40
50
y
---110 I I I I l20 30 40
50
~
~ list. index(x)
Retu rns the first occu rren ce of x in the list
-
append() list.a ppen d(x) App ends x at the end of the list
~
jDeertO list.i nser t{i, x)
Inse rts x in to the list in the position spec ified
._.. by i
copy() list.c opy( )
-estendO list.e xten d(lis tl)
Cop ies all the list elem ents into a new list and
-count()
-
list. count(x) Retu rns num ber of occu rren ces of x in the list
'
removeO list.r emo ve(x ) Rem oves x from the list
pop() list.p op() Rem oves the endi ng elem en t from the list
aortO list.s ort() Sort s the elem ents of the list into asce ndin g orde
r
reverse() list.r ever se() Reve rses the sequen ce of elem ents in the list
clearO list.c lear( ) Dele tes all elem ents from the list
\\e hn,~ U!'::l"d these m« th,,d s 111 J>1og 1nm 5 tn u11cl, •r s 1111,d "'•\•• ti
u rd on on c.,nn>J>I" hst.
,, .,
prin = num.
numl t('Ne
wlycopy () ted list
crea numl : ', numl )
num.t('nu
prin extenm
d(nu ml)r appe .
afte ndin g numl : ', num)
n = num.
,. • counft(5Q )
t mes 50 foun d in the 1 i st num .·
prin t~ No. o 1 ' )
, n
num.t('nu
prin remomve(50 ) r remo
afte ving 50: ', num)
num. t('nu
prin pop( )m afte r remo ving endi ng elem ent:
', num)
num. sort O
prin t('nu m afte r sort ing: num)
num. reve rse()
prin t('nu m afte r reve rsing : ', num)
num. t('nu
prin cl ear(
m) afte r remo ving all elem ents : ', num)
Outp ut:
c: \ >pyt hon lists .PY
No. of elem ents in num: s[10, 20, 30,
num afte r appe ndin g 60: 0th posi tion : 40,[5,so,10,60]20,
num afte r inse rting 5 at [5, 10, 20, 30, 30, 40, 50, 60]
Newly crea ted list numl : 40, 50, 60]
[S, 10, 20, 30, 40, 50, 60, 5, 10, 20, 30,
num afte r appe ndin g numl :
40 I 50 60]
J
No. of time s SO foun d in the list num:
num afte r remo ving 50: [S, 10, 20, 30, 40,2 60, 5, 10, 20, 30,
num afte r remo ving endi ng elem ent: 40, 50 60)
[S, 10, 20, 30, 40, 60, 5 , 10 ,' 20,
30, r40,
num afte sortSO]
ing: [S, 5, 10, 10, 20, 20, 30, 30, 40, 40, 50, 60]
num affte r rever ~1ng : [60, 50, 40, 40, 30, 30, 20, 20, 10, 10, 5,
num a ter remo ving all elem ents : SJ
[]
·ggest' and s,ndll<'"t r 1
,, ,g a, . en1ent<;
in a L'ist
f ,h.. '"11 ,11,w11p,,~ ,1111'( 11
11 1111rf
t 1t•''\ fl 11~1 Joi,, r'<11111p1t-, If llw 1
111"'' fl ,,11\ '
1111
''ll.
l!\t I'\'<'
Whir I
I , ''h1rr
r,'f,r,1\I~ I ,(11) ti nl give._ the bi . , th,,,,, lfh,•1i1ee,.!lt
rl"Jl 1 • i"•',,l'() # n2 gives the srngge ,;t elem •11(1 srn 11(' t
' \ . 1111 il 11 e,;t ent
O" w11 nl to u se these function 1 element
,11,t h . . . ii, )111 w
,( ,I<' . tht' list, OW IS 11 possiblr? For ti Ont ln fin I
tf l r11I~ 111
\I 11s Plltposn t lh, h,~"'11
tl ' ' 'W(' h ,111<1 s I
t'I s <>1.Jld I . rn., lc~t
~,i:1t• e will store the clements in a lis t Le ' ccVC'lr,p <111r O'.o.rn
f fill• w 2 . t s take th
~fl> [ZO , 10, 5, 0, 15] Cexan,pl
t1
~ _, ents here are represented as XIO]
C 1ISi n., ,
q~ .
'f
1 the other element 1s < small', we should ta.k
._;1grly, • e that other I
511w 1. [,·] <sma11 : sma 11 = x [ 1] e ernent as 'small' .
f X as.
st
rnparison starts from 1 element onward ,.,
the co . . . s, 1 value Will h
5ir1c\ the list. This logic 1s used m Program 6. c ange frorn till the
er1d o 1
tlll;.
progradl .
A Python program to find maximum and • .
minunurn elemen(s in a list of
e]eroents.- .
# finding biggest and sma1lest numbers in a list of numbers
x = [] # take an empty l 1st
rint('How many elements? '., end=;='') ·
~ = int(input()) # accept input into n
f'I'.-,grarn 7 shows how to sort the elements of o list using bubbk sort l<:r hniqU<'.
~ rt n t( 1 so , ~en ,1 ~~
O uU pl ll
~ \~ py th on em ~ rr . py 5
HOW m an y ~ l en ts ?
en te r ~l ~m en ~; J
En ~e ~ em en ~ : 4s
el em en t :
E nt er elef fl en r : 3
En ~e r el ~; 2 1 5 j 4 3 5]
2]
en te r elP_lm, ~n sC f , 4'
o r :i 9 i n a l f1 , 2 • '
so rt ed 1: is t::
s o f a n E le m e n t in th e L is t
ence
N u m be r o f o c c u rr tu rn s th
e nu m b er of ti
m es
t h at re
a P ar t1 cl. ll ar e1,.
co un t( ) m et ho d fll.,ll
Py th on pr ov id es am pl e,
I It
at ed 1n th e lis t. Fo r ex
;re pe
is m et ho d
n = x . co un t( y) un d in th e li st 'x '. T h r et ur ns 0
es '. :Y' is fo
nu m b er o f ti m u~
wt lJ re tu rn th e e li st .
un d i n th ke ,
el em en t is no t fo . un t( ) m et ho d .
Le t's ta
ou r ow n lo gi c fo r th e co co un ts ho w 'y as
th e efe
It is po ss ib le t
o d evel op us e a co un te r 'c ' th at .m an y tlll'le8rn"l:t
th e li st 'x '. W e w ill '-V ill be 0. W he n -., , i s fo un d · tht
to be fo un d in it ia ll y 'c ' va. lu e .Y Ul the ,,.
li st 'x' . In th e e l em
un d in th e er at es ov er al l en ts of th "lll
el em en t y' is fo ne ed a fo r 1oo p t h at it e hs t a/
t by I . W e
'c' wi ll in cr em en
fo r i i n x : if y == i '
om th e li st 'x ' in to 'i '. So , we fou nd th~
st or es ea ch el em en t fr
l. T hi s is sh ow n b y th e fo ll 0 .
Th is fo r lo op ld in cr em en t i va lu e by WJ.ng CO(jc
nc e w e sh ou
el em en t an d he
sn ipp et :
c= O
fo r i in x: c) )
i- f( y= =i ); C+ =1
} ti m es . '.- fo rm at (y ,
p ri n t( '{ } is fo un d{ cu rre n ce s of .,, ,.
gi c to fi nd th e nu m be r of oc J m the
n lo
ow
re pr es en ts ou r
Th e ab o ve c od e Pr og ra m 8.
. Th e s am e is sh ow n in
lis t 'x'
d • .
an y ti m es an el em en t o ccu rr e m th e lis t
to kn ow ho w m
Py th on pr og ra m
Pr og ra m 8: A . oc cu rr ed in th e
li s t
es .a n el em en t
w m an y ti m
# ~ ou []n t1#ng taho
ke an em pt y 11 st to n
x -
en ts ? ') )# a c c e p t in p u t in
ow m an y el em
n = in t( in pu t( 'H
e( n) : # re p ea t- fo r n ti m es
fo r i 1n ra ng en t: ', en d = '')
pr 1n t( 'E nt er el em
x, a1~, r-
na ti nt {i no utt.) ))
• ltl. . , , .
ul tu · l~ f\ l ~i'lm
·,. 1: (" ih e 1i st ts . nt: to tf\@ 11 It ,.
~r, • • x) I 6h ul 11 y ,
~ h-, H ~t
,n t(1 nr ,u t( ' t nt~,
r- e1 t1 M rH , l\ t.:o un t
: ') )
cc:O , ,n 1.:
r-or ;t (y e9 'i) : c➔~ l
pr ,n t ('{ } 1~ f ound { l times . · . fo rm at (y ,
c) )
O(ltplit rth on l; s . ~Y
c: \~~nY el emst en ts
HO"' el em en t: 40 . 5
Enter el em en t:
en te r el em en t: 20
30
Enter el emen t: 40
en te r elemen t : 50
ente~i st is : [4
rt,e el ement to0, co 20, 30, 40, 50]
un t: 40
en
40 t~, rs f ound 2 tim es .
. common Elements
·r,d in in Two Lists
f1 9 .
..;n ,eS , 1•t
is us ef ul to kn ow w
50rt1-e . hi ch el emen ts ar e re
• ~ ho la rs hi p fo r w hi ch pe ated in two lis ts. Fo
15 a sc a gr ou p of st ud r ex am pl e
were hip for w hi ch an ot en ts en ro lle d in a colle ge . ,
Th ere is an ot he r
he r gr ou p of st ud en
5cholaf5 ts go t en ro lle d. Now,
of the st ud en ts w ho en ro lle d fo r bo th we w an t to kn ow the
naIIles ak nl y on e • th e sc ho la rs hi ps so
sc ho th at we
wetD to t e ole m en ts ) in la rs hi p.1·Th at m ea ns , w e ar e su pp os ed to fin d ou ca n re str ic t
de bo th th e 1s ts. t th e co m m on
stu nt s (o re
_ e th e tw o gr ou ps of
st ud en ts
1,et s tak . setO fu nc tio n, as : se ~s tw o lis ts. Fi rs t of all , we sh ou ld co nv er t th e
ts us in
wto se ' g t(h st ) . Th en we sh ou lis ~s
ld fin d the co m m on
two se ts us in g in te rs ec tio n( ) m et ho d as : el em en ts m
the 1 ,·n te rs ec ti on (s et 2)
se t•
tum s a se t th at co nt ai ns co m m on
nu·s rn et ho d reh or re pe at ed ele m en ts
'[his gives us t e n ar ne s of th e st ud en ts w ho · in th e tw o se ts .
are fo un d m
present e d m
· Pr og ra m 9 . bo th th e s ets . Th1s
" l · ·
ogic 1s
~ Py th on pr og ra m to fin
d co m m on el emen ts
in tw o lis ts.
# fi nd in g common el
em en ts in two li st s
# ta ke two 1(1 s~ s
' 'K sh na ' 'sa ra sw
sc ho la rl
scholar2 == ['vRO ,n ay '•G ovriin at hi ' ' 'Govi nd '.]
d' ;T an us hr i',
SY ' ' 'v in ay ', •v ,s ha l' ]
# conve~t them in
s1 = se t( sc ho la rl )to se ts
s2 = se t( sc ho la r2 )
300 j f I
QutpUl
(:\>pyt hon , lis ts -~Y
c•vinaY', Gov1nd J
n,en we can store employee data like id nwnber,. name and sal eve em e,
list using the appendO method. After that, ii is possible to r~ details into lh
I 0. det,14
depending on id number of th e emP1oyee. Thi s 1s shown in Program Ployee '•:
~
PrograJD JO: A Python program to create a list with employee data an
particular employee details. d then retn
C\le