0% found this document useful (0 votes)
7 views18 pages

List

The document discusses the differences between lists and arrays in Python, highlighting that lists can store multiple data types while arrays can only store one type. It explains common operations on lists, such as indexing and slicing, and provides examples of creating and manipulating lists with different data types. Additionally, it introduces the range() function for generating sequences of integers to be stored in lists.

Uploaded by

Daksh Dhanraj
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)
7 views18 pages

List

The document discusses the differences between lists and arrays in Python, highlighting that lists can store multiple data types while arrays can only store one type. It explains common operations on lists, such as indexing and slicing, and provides examples of creating and manipulating lists with different data types. Additionally, it introduces the range() function for generating sequences of integers to be stored in lists.

Uploaded by

Daksh Dhanraj
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/ 18

f II \ I ' l l I•

LJ STS
. ,A ND.
fUPLES

sequenc c is 1) dntotyp c thnt rt•prt'H('I H H

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

ti o•· [io. •venu gopa l ' 'M' I so, ss I Gi


. , the S b . , 74, 66]
/ index .mg an d s l'icing
l
as1c o·pnr t·
1· ·t fron h' d . -=----:-__'-'.tJ\: ra u ons· fl ct·
,,, bers 1p an 1te raf otcnn tinn
!Q.n Opera ~ -· n 11l&_length , concnnd"
\ ·N : ..tit1Q.fl, incm
,cq\.l es like strin gs,
,~~ tuple s or dicti onan es. ~can be pcrro rmcd on lists oiiie ;

~ follow ing prog ram, we are creat ing lists w· .


111 tlle . the list elem ents . tth differ e nt types of Ci "
l men ts nnd nlso
. playi ng
d1S - - .

1 : A Pyth on prog ram to creat e lists With .


e.-ngralll d1fferen t t:yp
es of elem ents.
p- 11 a gene ral ~ay t9 cr~a te lists
1 crea te a list with inte ger numbers
m - ~10, 20, 30, 40, SOJ
nu.n t( Tota l list= ', num) # dis 1
P~in t('Fi rst= %d, Last = %d' % cn 4 ~[bJ
tota l list
P # last elem ents ' num[4])) # disp lay firs t and
#cr eate ! lis! with ~!ri~ gs
[ RaJu .' V~ni name
names =Tota ' Gopa#l"'di "Laxmi "] .
l list= , s)
6J
•nt('
P~in t('Fi rst= %s, Last = %s' % Cnam!~[1 enti re list
P # and last elem ents • names[3])) # disp lay firs t
# crea te a list with diff !ren t elem ents nu']
x = [10, 20, 19.5 , ~.55 , Gan~sh la~ , 'Vish
rint( 'T9t al list= , x) # d1sp enti re . t
Ppri nt('F irst= %d, last= %s' % (x[O x[S] )) 1 1} d '
J,
# elem ents
isp 1ay firs t and last
outpu t:
c:\>p yt~o n lists .py
Total list= [10, 20, 30, 40, SO]
Firs t= ;o, Las! = ~o, , .,
Tota l l1s~= [ RaJ u, ~an, , 'Gop al', 'Laxmi']
Firs t= ~aJu , Last = Laxm,
Tota l list= [10, ~O, 10.S , 2 .55, 'Gan esh', 'Vish nu']
First = 10, Last = Vishnu

creating Lists using range() Function


• We can use rang e() fun ction to gene rate a sequ ence of integ ers which can be stored in a
list. The form at of the range(} funct ion is:
rang e(sta rt, stop , step size )
If we do not ment ion the 'start ', it is--;; sume d to be
O and the 'steps ize' is taken as 1. The
exam ple, -
range of num bers s t ops one elem ent prior to 'stop' . For
rang e(0, 10, 1)
ZtJ6 ('hnp\l i in fro!Tl O to 9, nR: [0, I , 2, 3, •I, 5, r, 7, S, qi
(tltC f1\llll hers r·rH1 ,r1
t'n t
Thi~ \\'Ill grl1C tr

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 , • '

Ot1tpt1t: thon 1; sts. PY


C: \>PY 2 ' 3 4 ' 5 ' 6 ' 7 I 8 ' 9 ' I

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

updati n g t h e E lements or a List ------


L,, "' 1:' o n · rnutof-.J11'· . ft rn co n
or ~ ,.,,. ,r th e c Jcrn <· nt o or o
o _ W'C ca n ,-,,,_odif:Y th e c o n t e n ts_ o f a H at. W e
-✓ C& ✓r ..... ~ ,, •
1J a 1· dcpcnd J r.1-g u p o n o u r r e quJre :rn e:nts' - ""PPend
.A ,· 0
nn< ~
c •n_clln...,, ,.,..,.., c .J,~rn co t rnean o addinB;: an e lem
e- l cmrn t 10 th e JJ u t , vvc u h o u l d.r "LI.SC th e appen - - d- - j) m e t h o d . In t h e
1
d e n t a t t h e e n d of" the 1st. -
· -w1ng
To
ex.a_
---..•-...
.;;, r.
f"oJloe 1 e. m ent append
c r,o<in,< o H 6' w " h c •c=cn<e , ro= ' <o 4 an . <hen a p p e n d i n s a n ~
1st - 11s1:( r- a n g e ( 1 , 5 ) ) . # c r eate a 1 ; s t u s ; ng 1 ; s t C )
g
=Pie
·
. W e <P o

·
= ·-
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

i • -1 # las t elem ent


while i>= - 5: # dis pla y from -1th to -5th
pri nt( day s[i] ) elements
i-= l # dec rea se the pos itio n eve ry time
.
_!1J0 1th ph I 1II wfti ,, \\ ' nr1 d,npfr,ylnf' tit, d
. fl1 J'111~1 till1 1 "It t I I
11\l!I Ii 1 111 t l11\\I ,, , '{r1 ,wo ,1,11, ,, or w11y11
,n 1, h1l 1 Im I
otdN ,,~IJq,
~
~
'" 1il'lf1IHY""' I il'IJH 111, ,,, H " " " ' r, 1
• · J\IM" fl'"g""' 1 .,, ' I"' •r
~p•"' 4: A
1
,mro" In r rvr rs• ur tier
di ,p pvl ng ll)1 '.,oo,,d,iY' , ' 1u1•1day' , 'w,,dnr•sd,, t' , h
1

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

/ Concatenation of Two Lists


we can simply use '+' operator on two lists to join them. For example, 'x' and y
lists. If we writex+y, the Ii st 'y' is joined at the end of the Ji st 'x'. are "'·

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

Aliasing and Clo~ing _Lists


Giving a new nam e to an exi stin g list is cal led 'ali asin g' The new
, For exa mp le, tak e a list 'x' wit h 5 · nam e · all d 'ali
ele me nts as 1s c e as
name- .
X = [10 ,20 ,30 ,40 ,50 ]

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

Aft er mo dif ica tio n


• .1ng
cat ion s ;n a11as
Fig ure IO. I: Eff ect of mo difi
lis ts ' h e s h ou lct
wa nts tw o in de pe nd en t
en ce ' if the pr og ram me r no t go for
H , he sh ou ld us e clo nin g or co py ing.
the oth er ha nd a1,..;,!i. (,
ex ist ing ob jec t (or lis t) is ca lle d , 1 .
Ob tai nin g eX act co py of an as : co ni ng '. To cl0 ne ·
g op era tio n 1
ca n tak e he lp of th e sli cin • Ii, I "·

# 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

Be for -e mo dif ica tio n

x ---. I I I I I I
10 99 30 40
50

y
---110 I I I I l20 30 40
50

Aft er- mo dif ica tio n


yin g
cat ion s in clo nin g or cop
Fig ure I 0.2 : Eff ect of mo difi
'th t in i 1 in• 'f1 <:,th
t;1ft'\
4Ut V("d ~ y l I Ht I} < 1t fflty l
,, l'
d
,:ill l,r :-,0t, l
l,lt t'
,,,rt I hr foll<n• ·~ ~t httrn ,-, t
<~~ ~ .({:fiV() t x ,~ (Op1 ~~ IS v
~ h hl\t lfl,4 llu~ . n scpn tntc __
n "11'.' ("{')Jl'
, .... ,,c 1 ndt• pcnd c.ut Hen ce a.nv "vJW of JI h
t ~ (' T'f\1'nt!\
\\1
c ~ !An
c, •• ' rnoo 1fka t1
dc.•pic-1~ tlw conc ••iu of tlon ,no
1rt f'!Q.:-\1~ 2
..n r- •h
011s to -X '-'
~ and c-opyinr.
,;ti-~ ,

odS to process Lists


~etfi flJI'lc . 0
JcnO is usef ul to find the
t10 num ber of I
111r. .on 9.S: e emc ms in a hst \11
ft.JOcU 1en (lis t) e cen U"'l.. thi ..
n •
•. dica tes the num ber of elem ents of the
}'{ere,
'Tl 1I1 b"
r1 . .
_..-l\ func 000
that retu
.
rns 1gge st elem ent in th st. S1m1lor t 0 I<'n() func tion. Wt.
.
tnvu 11 st elem ent m the list. Othe r than e 1ist. Also th . hou..
J1l9 e thes e fu . e m1n0 func tion retu rns , ."
tJ,e s prov ided by Pyth on to perf orm vari ous oper nct1o n th
af . ere ore vano u~ othe r
rnttbod_s Tabl e 10 . 1:
hOWO Ul ions on lists . Thes e mf'th ocb or~
5
. The List meth ods and their Description
f..,.. 1 0.1.
Example Description
~ l
~
list.s um()
sutnO Retu rns sum of all elem ents in the hst

~
~ 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

App ends listl to list


retur ns it

-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.
,, .,

~ t h O J 1 prog ioin t o unde r stan d lis t p 1on·s


..- .. - &-
srny u,ctl
' l<H l ci
# pyth on • ~ li s t meth ods
num = [l0,2 0 , 30,4 0 , 50]
n ~ le n ( num)
prin .
t(' No. of elem ents ,n num: , n)

num. appe nd(6 0) endi ng 60: ', num)


p r int(' num a f ter app
num .insem
prin t('nu rt(0, 5) r inse rtin g 5 at 0th posi tion
afte : •, num)

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~ .

11 st clc~ general represented as x[i] . We '. x[l]. ··· X.[41. l'hat


file re 1J1 w, 11 tak th mean h
1 list 1118 nallest one as: e e first elern s t e clements
~c e s1 ent as th b' • 1n
8
1so ss . - [OJ
b,g-X [OJ c iggcst and
51113,, :::)(
are 'big' and 'small' elements with
jJJ comP . h ld b other ele
\le w 11. big then 1t s ou e taken as 'big' Th tnents in the I'
I
e1er11efl·f sx[i]>big:
> '
big= x[i] · at rnean 1st. If the th
s, o er
, . (

'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

for; in range(n): # repeat for n times


print('Enter element: ', end='')
x.append(int(input())) # add the element to the list x
print('The list is: ', x) # display the list

big=x[O] # initially 0th element becomes maximum and minimum


sma 11 = X [OJ

for i in range(l, n): # repeat from 1 to n-1 elements


if x[i]>big: big= x[i] # if any other element is> big, take it as
# big
10
,
I 1f llny 0 th ,. cJ~m~nt 1i ~
if ~li)<:SmaaH: ~ml I I • x [f ) I
f take ,t ~ small . ffLlJr
1 ,s p la y max and,,, 1
m is : ', b ig ) d " elemen ts
u
prfot('Maximu11 is : • sma1l)
print('Minim
O U lp u t:
s.~Y5
(:\>pythoneleil1,ist
en ts .
How ,nan }'
ent: 20
Enter e1emen t: l0
En te r elem
Enter element: ent: 5
20 J
Enter element: 15 15
Enteli r elem 0, 10, 5, 20,
The s t is : [2
"4.lxi,num is : 20
Minimum is : 5

orting the List Elements a li st . This met


hod
S o d to so rt th e
el em en ts o f
Cctn u~
ve
l-
th e sort() m et h
Python provides
as : th e ele
x. so rt () If w e w an t to so rt ents of
li st 'x ' in to as ce n d in g o rd er .
- T e ' . th e sort() m rnth as • the/'1st
m
Thi s will so rt th
e . ' v er se - ru e . od
rd er th en w e ca n m en ti o n re ·
o
into de sc en di ng '
True)
x.sort(reverse=
d in g o rd er .
so rt th e li st '.x ' in to d es ce n av e to develo
This will rt () m et h o d , we h
so rt a li st w it h o u t u si n g so
e 'n ' el em en ts fro P our OWrJ
S up po se, we w
ant to n iq u e, all th to nare
te ch ni qu e. In this te ch it h th e im m ed ia te 1m O
logic like bubble
so rt
xU} is co m p ar ed .
w e em t )(U+//.
en
en t o f th e li st h an g ed ) si nce .
first elem (or m te rc ~ i.
10 ascenctih
ta ke n an d the . 1], th en th ey ar e sw ap p ed . W he n tw o
than xLJ+ · th e fi rs t pla ce e1ements are
If xU] is bigger le r el em en ts to b e m ss er by 1. Whe
ct the sm al ed b ec o m es le
or de r we expe en ts to b e so rt n tbere are
, th e n u m b er o f el em
' a n d w e ca n ab o rt so rt in g 8 pose, we
interchang ed
ill b ec o m e 'Fal
se · up
d, th e 'fl ag ' w
foun
no more sw ap s so rt in g:
llow in g el em en ts for
give the fo 3, 2 no swaps · we get:
origina l li s t: 1, 5, 4, ements. 1 is sm a ll e st hence
1 with3,oth2 er el
compa1re, 5, ith
5 with 3 • 5 w 2. We
4, swap 5 with 4 '
h o ther el5ements. et·
pare 5 w it
Com get: 1 , 4 , 3, 2,
ap 4. w it h 3 , 4 with 2. we g . 1' 3'
. sw
o th e r elements · ,
g e t: 1, 2, 3, 4 5
compare, 44, w5ith w it h 2 . we
2 swap 3
pare 3 w ith o th e r elements.
Com
•=b b• t

figure I O.l : SW3pping :t ;rnd b VJluos using o ccmpor.iry var i.iblc t.

f'I'.-,grarn 7 shows how to sort the elements of o list using bubbk sort l<:r hniqU<'.

~ Pyrhon p r o ~ to sort the list elements using bubble s ort technique .


sorting a 11st us~ng bubble so~t technique
1 create
1 an empty 11st to store integers
X = (]
store elements into the list x
1rint('How many elements ? ', end='')
~ = int(inpu t()) # accept input into n
for; in range(n) : # repeat for n times
print('En ter element: ', end='')
x.append (int(inpu t())) # add the element to the list x
print('Or iginal list: ', x)
f bubble sort
flag= False # when swa~p~ng is done, flag becomes True
for; in range(n - 1): # 1 ,s from Oto n- 1
for j in range(n- 1-i): # j is from Oto one element lesser than i
,f x[j] > x[j+l]: # if 1st element is bigger than the 2nd one
t = x[j] # swap j and j+l elements
x[j] = x[j+l]
X[J+l] = t
flag = True # swapping done, hence flag is True
if flag==Fa lse: # no swapping means list is in sorted order
break # come out of inner for loop
298
A~ ~ f g n tn f t ie
l V A lu ~ f t1 fla {f
1

~ 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

, ft ~"ttrsr t;on of t:wn set~


~1 ~1 ~ntcrscct1on(s2)
, conv<rt th• resultant set into a list
c~n o 1ist(s~)
, dfsp1aY thP- 11st
pfint(C~)

QutpUl
(:\>pyt hon , lis ts -~Y
c•vinaY', Gov1nd J

storing Different Types of Data in a List


n,e 1,eaulY of lists 1s that
· fl tcan store different
theY b ·types of eleme nts. For
string It . pl..
. .
store an integer, a string a oa type nwn er etc. in the same .
over ana el<ant p,,,
.
rctneve the elements rrom the list. This has advantage for lists · IS also can' ,. ·~
list emp' as an emPIY list as: ys. We ,,;,,
emP • [] ,,.,,,

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

# retrieving employee details from a list '


emp = [] # take an empty list
n, int(input('HOW many employees? '))#accept input into n
for i in range(n): # repeat for n times
print('Enter id: ', end='')
emp.append(int(input()))
print('Enter name: ', end='')
emp.append(input())
print('Enter salary: ', end='')
emp.append(float(input()))
print('The list is created with employee data.')
id= int(input('Enter employee id: '))
ior~
display employee details upon taking id
range(len(emp)):
1~ ·
1f 1 i J:
d==emp [emp[i+2]))
p~int('Id= {:d}, Name={·.s } 'Sa1ary= {:.2f}'.format(emp[i],
emp[i+ll.
break

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy