to create lst, one thing
mutable (ic, ifiable}
memory addres eres OF alin pla Ge table
n TESS of a list will not change even after you
f the tw
Lists and Dig one ‘0 mutable types of
é ‘tionaries ay types ; all other
ata types of Python st” immutable ee Pes all
7.2) Creating Lists
To create a list,
i | Puta Number. ‘ 7
icate the start and Of expressions in
aye brackets.
(2, 4,6) end of the list, and Separate the items by
Cabe, ‘depy
(, 2.0, 3, 4.6)
oO
Thus to Create a list you can
l=[)
L=[value, ...)
write in the form given below ;
This construct is known as a list display construct.
Consider some more examples :,
© The empty list
The empty list is { J. It is the list equivalent of 0 or and
like them it also has truth value as false. You can also
create an empty list as :
L=1ist()
It will generate an empty list and name that list as L.
© Long lists
That is, use square brackets ty
commas. For example :
‘an contain valves of mad)
i it it across
If a list contains many elements, then to enter such long lists, you can split i
several lines, like below :
» 169,
sqrs=[@,1, 4, 9, 16, 25, 36, 49, 64, 81, sre gears
196, 225, 256, 289, 324, 361, 400, 441, 484, 529,
just in the
Notice the opening square bracket and closing square brackets appear just
beginning and end of the list.7: AUST MANIPULATION
o
© Nested lists .
A list can have. AN ek
fement init, whiet
- Gtete eh tenn at, Sct nt ctl nent t 68%
© nested list with me
four clemer
hott wa SS £3, 4,18, 6] andl 7, LaLa} clement in lint (5, 61.
IS, 6] a8 ono clomont,
creating Lists from Existing Sequences
You can also use the by
given below stein Uist type
‘object to create tists from, sequences as por the syntax
L = List(
can be any kind
creates the individual elements 9 sip ence object including strings, tuples, and lists. Python
you pass in another list, the list fees individual elements of passed sequence. If
Consider following examples : copy.
>>> Id = List(helio)
pln a grt fo ana quae —
a Vy‘) 1 general individual elements from the
Invitees of the ring
pote (W er ty)
>>> 12 = list(t) ee ie ‘created from another sequence —
>>> 12 ‘It generated individual elements from the
Iw, 'e, ty] individual element ofthe assed tuple
‘You can use this method of creating lists of single characters or single digits via keyboard input.
Consider the code below :
11 = list(input( ‘Enter List elenents: *))
enter List elements: 234567
Sola ew. ereatetheeements of it using
(2,3, °4,°5,°6,°7) ‘ach of the character Input
Notice, this way the data type of all characters entered is string even though we entered digits.
_ To enter a list of integers through keyboard, you can use the method given below.
‘Most commonly used method to input lists is eval(input()) as shown below :
be ee i ) tries to identify type by looking at
List = eval (input( “Enter list tobe added:" )) «——— ule idly oy ang
print (“List you entered :*, list) ae
when you execute it, it will work somewhat like +
Enter list to be added: [67, 78, 46, 23]
List you entered : [67, 78, 46, 23]
Please note, sometimes (not always) eval() does not work in Python Shell. At that time, you can
run it through a script or program too.a
COMPITER SCRE WITH THON 5
ee ee ee een emeet
mus
oran('S 9+)
will give you renal as 13
Staulary, folowing code fregment
Y= eval(“3e19")
Print(y)
‘will print value as 39
Sacra) ca erp an expr fives a sng you can we wh ap)
var] « eval (tnput(“Enter Value;"))
Print (vard, type(vaer))
Executing this code will result as :
Enter value: 15 4 3
18
wit erat jt 2 ly nerd thsi 1503 a 18 but a red term as tae, Tan
with eval(), 1 You ener a negro oa vale. al lurpret the vars a the need
wal Apr (“Enter Value: Vard = eval (input (“Enter Value: *))
‘ (vart) (Pednt(vari, type(vari))
Enter value: 75 Enter value: 89.9
75 89.9
You can use eval) to emer alist or pe also. Use { }10 enter lists” and (©) 00 emer tuple values
r Value: ")) isevall ‘valu
ieee es = “z
ue: (1, 2, 3) Enter value: (2, 4, 6. 8)
ficeecr en auc ae
7.2.2 Accessing Lists
crete, te nan, Clements and certainly there i, But before we start sccraeng wedivcauel
ee aaa ah es afl ace eee eres
how individual elements are accessed JC ists = the way you access string elements. Following
‘subsection will make the things very clear to you, [ bet !
ee(0) Hom ats ay itarmaty srganicnd
Nope
Thuis, you can access the tint chements juss tike you acrese 2 :
string s chemenes e.g. Latta} wk
you the element at ith index ofthe lit: Llslacb] will ve you elements berwcen mciouen sw
b- Land so on.
Put in another words, Lists are simular to strings in following ways
© Length
Function lea(L) eeture the number of items (count) tn the list L.
© Indexing and slicing
Lif eeturne the tiem at inden # (the first tem hae inders 0), and
Lf ts) | returns & new het, containing the objects at indeurs between 1 and ) (exchading,
dnder j ).
© Membenhip operaion:
Both tn’ and ‘not Int operators work on Levty just like they work tne other sequence.
That ss, tells of an element ia present in the list ve pot. and rot 9 dows the oppemite,
© Concatenation and replication operators - and”
The + operator adds une list ws the eral ot another. The” operabor repeats 4 het, We shal
be taluang about these fe: operations at 2 laser srcscat 75 Last Operances,= COMPUTER SCIENCE WITH PYTHON ~ x,
Accessing Individual Elements
As mentioned, the individual elements of a list are accessed
through their indexes. Consider following examples :
ile accessing list elements, if
eons a [you pass in 2 negative index,
rience) {bython adds the length of the
* [Isto the index to get element’
cae ward index. That Is, for a
ee element list l Lf-5] wil be
vowel ternally computed as:
arertaa) L[-5+ 6] =£(1), and 50.0
: rentenrn ill
>>> vowels[-5]
S
Like strings, if you give index outside the legal indices (0 to length — 1 or — length, - length +1, ...,
‘uptill -1) while accessing individual elements, Python will raise Index Error (see below)
>>ovonels = ['2','e "t,o, wv]
>>> vowels[5] <5 eal der mowed hs cont
be ted 0 aces individual element
Traceback (most recent call last):
File "", line 1, in cmodule>
vowels[5]
IndexError: list index out of range
Difference from Strings
Although lists are similar to strings in many ways, yet there is an important difference in
mutability of the two. Strings are not mutable, while lists are. You cannot change individual
elements of a string in place, but Lists allow you to do so. That is, following statement is fully
valid for Lists (though not for strings) :
L[i] =
For example, consider the same vowels list created above, that stores all vowels in lower case.
Now, ifyou want to change some of these vowels, you may write something as shown below :
>>> vowels[2]
a Notice, it changed the element in
>>? vowels place: a" changed 10 ‘A no new
(A, 'e, 'f, "0, ut] list erected ~ because Lists are ‘are similar to strings In
SESE CEG ‘MUTABLE, ny ways like indexing, slicing
{and accessing individual elements
>>> vowels ‘But they are diferent in the
(A, 'E, ‘0, ut] ‘sense that Lists ore mutable
‘hile strings ae not.
Traversing a List : ad
Recall that traversal of a sequence means accessing and processing each element of it, Thus
traversing alist also means the same and same isthe tool for it, ie, the Python loops. That is
why sometimes we call a traversal as looping over a sequence._forlooP makes iteasy to traverse or loop over the items in alist Pet fotlowing 7"
pe
process each iten here
example, following Toop shows each item ofa list L in separate ines *
pelhe +g, th,‘ '8)
aint?
for
print (2)
se above IOP De eereresd eM
sosleet
So,
1 works
How variable a in above Toop will be assigned the List elements, one at % time.
Joop variable ‘a will be assigned ‘P’ in first iteration ‘and hence ’P” will be printed 7 #"
soa will get element 'y’ andy’ willbe printed; and so on.
weed to use the indexes of elements to access them, you
per following syntax
range(Len(L)):
for index in
List [index] here
process
Consider program 7-1 that traverse, through alist using above fo
fir Lin separate Lines along with its index.
‘y’ Lin separate lines 21079 with element's
rogram to print elements of st + wie
both indexes (positive and negative
Lela W, et to Bf
Length = 1en(L)
for ain range(iength) +
print ("At indexes”,
a, "and", (2~Jength), “elenent 2, Uta))
ample run of above program iS:
-6 element : 4
25 elenent :
-4 elenent : ©
nt indexes 0 and
‘at indexes 1 and
‘at indexes 2 and
At divdexes 3 and -3 element: 7
iat indexes 4 and -2 element: ©
at indexes 5 and -1 eTenent : ¥
ators of Python, ie,,<, >) ==; != ete
Jexicographical order.
re equal and the
Comparing Lists
‘Youu can compare two lists using standard comparison ope
Python internally compares individ) ‘clement of lists (and tuples) in
This means that to compare equal, each coma ing element must compa
two sequences must be of the same IYPe "+ having comparable types of values.a 234
Consider following examples:
PAD ROE Fp,
pee a t2 105)
>>y Utama
True
>> Uwe La
False
cpa PURO ><, cna een fo st at
Comparable types , otherwise Python ai
—
COMPUTER SCIENCE WITH Pron _»
3), (1,2, 3)
I give error.
Consider the following considering the above two lists :
Meteor
se iota nti
False ‘For second comparison, as the values are nok of
>>> L163
Traceback (most recent
File “”, line 1, in
<* Rot supported between instances of “int? and ‘list’
Python raised error above because the i
(4, 2, 8, 9) < (9, 1]
(1, 2, 8, 91< (1, 2, 9, a3
True
(1, 2, 8, 9} < (4, 2, 9, 19)
True
(1, 2, 8, 9} < [1, 2, 8, 4]
False
9<4 is False7: UST MANIPULATION,
os
50, for comparison Purp &
applying all the comparison ¥,73"40n internat =
eae les that ally compar, ae
pop am (2, 3] YOu have rea ioe Individual elements of two lists,
paces . ler. Consider following code : |
prem ['2', ary Fal
oo d= (2.8, 3.9) as
oo e= (2,3, 4) earn
False X pe
ee fore
>>>dewa | 4 Pion pal pe of dames
True ‘ud compared valu ony
)
>>>ace
True
Buty mst hae
With matching me MUtber of elements and match
— ine values ae considered qual)
covering it here. a
comparisons but we are not
73. UST OPERATIONS
‘The most common operations that
ei £ ou i
and slicing lists. In this section, we a Ee a joining lists, replicating lists
t .
73.1 Joining Lists a
Joining two lists is very easy just like
operator +, when used with two lists, joins bene a
i : tion, literally ;-) . The concatenation
joins two lists. Consider the example given below
>> Ast =[ 2, 3, 5]
>>> 1st2=[6, 7, 8]
>>> Ist1 +1st2
Signer
[1, 3,5, 6,7, 8] al eae oe ae
‘As you can see that the resultant list has firstly elements of first list Ist and followed by
elements of second list Ist2. You can also join two or more lists to form a new list, eg,
>>> Ist1 = [18, 12, 14)
>>> Ist2 = (20, 22, 24]
>>> Ist3 = [32, 32, 34] Tet
operator i used to concatenate
yop Ist =Isti+1st2+1st3 < the individual its get nw
>>> Ist ee
[10, 12, 14, 20, 22, 24, 30, 32, 34] a
The + operator when used with lists requires that both the operands must be of list types. Yo
cannot add a number or any other value to alist. For example, following expression will resu
into error :
List + number
List + complex-number
list + stringey a :
COMPUTER SCIENCE WITH PETHON _
Consider the folowing examples
>> Asta = [10, 12, 14) errors generated wien arching
>oastae2 ‘ee tastrin hodlal ott
File “epyshelii
Astae2
Typetrror: can only concatenate list (not “int*) to list
>>> Ast. sabe"
#42>", Line 1, in
Traceback (most recent call last):
File “", Line 1, in cmodule>
Ast2 + "abe"
Typeérror: can only concatenate list (not “ste*) to list
7.3.2 Repeating or Replicating List
Like strings, you can use * Operator to replicate a list specified number of times, eg,
(considering the same list ist = 1, 3, 51)
ER) Re,
[2, 3, 5,1, 3, 5,1, 3,5)
Like strings, you can only use an integer with a * operator
when trying to replicate a list.
7.3.3 Slicing the Lists
List slices, like string slices are
out. You can use indexes of list
per following format :
seq = L[start:stop)
the sub part ofa list extracted
‘elements to create list slices as
‘The above statement will create a list slice
start+1, start#2,...., stop-1. Recall that index
on last limit is not included in the list slice, The list
slice isa list in itself, thatis, you can perform
all operations on itjust like you perform on lists,
Consider the following example :
99> Ist =[18, 12, 14, 20, 22, 24, 30, 32, 34]
>>> seq = Ist [ 3: -3]
>>> seq
(28, 22, 24]
>>> seq[t] = 28 lst th elements fang
ie — eee aa ne ee eer ae ae
[20, 28, 24) a
ace "Ret includ
eee at esot
7 UST MANULATION
1 indexing, j
or normal indexing, if the resutt,
ion. Slices Sulting index j
eae eee oundaic%. Sutside the tit, i Es
vetween ae laries. For the starp ait instead, and the result yi cae ieee
pounds), simply Stop gi will simply contain all items
vat aling ary nPly rebum the clement aes list imits ina lst slice (ie,, out of
for example, consider the following ; m specified boundasien 2
yoy Ist =[18, 12, 14, 2, 22
>>> Ist [3:30]
(28, 22, 24, 32, 32, 34] (ing unpe tn way beyond th se ofthe
pop Ist [-15 27] thn re ime jo Bt fing
40, 12, 14, 20, 22, os
t cae iting lve tim much ler, bt Python
eur lament rm fling rng 15 onward <7
>>> L1[2, 3, 4, 5, 6, 7, a
pr LA [23 5] Legal index range is 046 and 7-1
» 24, 30, 32, 34)
[4.5.6]
mas ery
[8]}+———
rr yon ture ts
>>> L1 [10 : 20] per len range
—_ Both limits are out of bounds
J
01+ ———~ bon gives no eror and returns an empty sequence as
ro element of Lt has index fling in range of 10 '0 20.
Lists also support slice steps. That is, if you want to extract not
consecutive but every other element of the lst there isa way out
he slice steps. The slice steps are used as per following format: _tstrt: sto: tsp] Seale Es
seqe ufstartsstop:step] parece ae
Consider some examples to understand this. and stop, not inluding st0P-
skipping step-1_ elements in
Hoven
pp ist i
eal
[30, 12, 24, 20, 22, 24, 38, 32, 34]
a A tnd ey nd lent ip | eet
boo Ast[@: 10:2] fae ry nd dee St
ee
1 note every Sr element, skip 2 elements
>>> Ist [2 # 10:3] ei
[14, 24, 34]
(7 No start and stp given. Ont sep is given a 3. That 8, rom
po Ast: 31 Na a, pik every 5rd clement forthe Hit lice
[10, 20, 30]
Consider some more examples :
seq=tl #get every other item,
seq= Ll #get every other item,
starting with the first
cartingwith the sixth elenent, t.e., index 5 ,™
COMPUTER SCIENCE WITH PYTHON ~ 4
Bh.
ns AEimB% IE you lve [:: =t}, ft will reverse the Ust © for list say
List =[5, 6,8, 11, 3), following expression will reverse it
>>> Last Cy
Ba,
tres which cana every ether ekoment ofthe His between indexes 5015. Program should also
f 72 Extract two Hist-stices cut of « qiven list of numbers. Display and print the sum of elements Of firsy
2. Asplay the average of elem
nents In second list slice that contains every fourth element of thelist
The given list contains numbers from 1 0 20.
Ast=[a, 2,
slei = 1st[s
sled 1st(::4)
3,4) 5, 6, 7,8, 9, 18, 12, 12, 13, 14, 25, 26, 27, 18, 19, 20]
5:2]
Sum = avg = 0
Print ("Slice a")
forainsici:
Sums a
rat Co ende a) Sample run of above program
ry print ("Sum of elements of slice 1:", sum) slice 1
} Print (“Slice 2") 681012 14
| sum=@ Sum of elements of slice 1: 50
i for ainsic2 : stice 2
aes 1591317
print (8, end *) ‘Average of elenents of slice 2: 9
print ()
avg = sum /len(sic2)
Print ("Average of elenents of slice 2:*, avg)
‘ Using Slices for List Modification
You can use slices to overwrite one or more list elements with one
or more other elements,
| Following examples will make it clear to you :
>>>L= [Yone", "two", "THREE")
>>> [0:2] =[@, 1] ¢—_asining new values 10 list sce
>ook :
(0, 2, "anes EGE Nt Ht ecg
>o>Le[one", "two", “THREE"]
>>> [0:2] ="a"
>ok
(Pat, THREE] EH Ne wa te one
Inall the above examples, we have assigned new values inthe form ofa sequence. The values
| being assigned must be a sequence, ic, a list or string or tuple etc.7: UST MANIPULATION
owt
For example, following Assignment ig 239
port = [1, 2, 3)
por La [2 OT
poo lt ‘Shing tea asp
Typeérror: can only assign an iterable
But here, You should also know somethin oo
length ofthe list, it will simply add the veuco or aaa
>>pl1=[1, 2, 3] o
11 [10 : 20] ="abca» <——___
mpl ] = “abed 2 ror even though it sce its ee ouside
poo Ld eine Now Pon wil apend the leters
[1,2 3, 'a', "bY, "et, tary fe
74 WORKING WITH LISTS
Now that you have learnt to access the individual elements of a list let us talk about how you
can perform various operations on lists like : appending, updating, deleting ete.
Appending Elements to a List
‘You can also add items to an existing sequence. The append() method adds a single item to the
end of the list. It can be done as per following format :
L.append(item)
Consider some examples :
>>> Ist1 = [10, 12, 14]
>>> Lst1.append(16)
>>> Ast ‘The element specified as agent to append is
[18, 12, 14, 16] a eld hee of eng e
Updating Elements to a List
To update or change an element of the list in place, you just have to assign new value to the
‘element's index in list as per syntax :
LI’ dex] =
Consider following example :
>»p Ist = (10, 12, 14, 16] ‘Seeenent plating a clement (Sella!
>>> sti [2] = 24 <—————" hing inde 2) he its
do>Ist1 Display heist se the updated Uist
[10, 12, 24, 16) <——__-_ST
PP
Peery Semone ram a igs
XS am akon sermon tome wm dats The el saapoment sw wat Fone AH HNVEtvAL
RM STAN MONS AT AEM ARNRTAR NY A TRO TL RY De None in Per aya ven DelOW 7
SONATE SEMNCE ADH PYTHON Oo
Jeane) Bry remaee element at Liter
SSSAPEN SATAY] w ta pemave element dn List slice
Comsskee aallomemg pepe:
~ STARR BALSA 7 BB, NW UY 2B, 1a 94, 28, 36) 175 18) 19, 38)
SRST] ERT se eee a mt 1 te my
SS S017 gee dad HO AN
BoB SHANG ~B BW BW BB 44, $26, 17, 18, 19, 20)
SOE EERE REA) <——————__ nee at sents toon tnd 209 18
ast mame. Cama here spe Pek?
BSR 7S 2, 28, 9, 2)
Roem ae Sal Aegean omy ng. ded Bt, TL will delete all the elements and the list object too,
Ache aS no chiens by tho name Ie woud be eating,
Naw sam RS SS PAPC) methad Ww remove sine element ot list slioes, The pop) method!
SEMNWS am Inieidual Rem and retams i, The del statement and the pop method do pretty
ack dhe sume SINE. Hep Tat Pap method alk reams the removed item along with
Ssketing R Som Bk, The pay) mdhad $s wad as per following format :
FOR, > istmpaa) JB skews, Alto pont eteuns the
a stement too,
“The pop’) method is aseful only when you want to store the el
aloment being deleting for later Uso, a,
Stemt = 2 gen) # last item
Stem2= 2 qapi@) otirst iter
ares < Lp) #sixth item
gue Noa can Re Heemal, Hem and HtemS in your program as per your requirement,
y
LISTS 1N PYTRON ~1 .
Progress In Python 7.1
>
This PoP session works on the objective of practicing List Manipulation operators,sometimes you need to make a ed
ee SOPY oF als and you generally tend wo doi using ass nt )
» 2, 3] Tee ignment, e.g.
bea he oy ftw
shown in adjacent figure
twill work fine as long as we do not modify ls
S dif ii
reflected in other because a and b are like ape ae
>>>asf1, 2,3] for the same list, See below :
>>bea
>a] <5
>a
(2, 5, 3] See eb A
1,5, 3]
See, along with list a, list b also got modified. What if you want that the
copy list b should remain unchanged while we make changes in list a?
‘That is, you want both lists to be independent of each other as shown in
adjacent figure. For this, you should create copy of list as follows :
b=list(a)
Now a and b are separate lists. See below :
>>>a=([1, 2, 3]
>2>b= list(a)
>>>a[a]=5
>a
15,31
pane ‘Now, list isnot reflecting the changed
[1,23] (ee akan List b is independent of list a.
>>
‘Thus, true independent copy of a list is made via list( ) method; assigning a list to another identifier just
creates an alias for same lis.
75 LIST FUNCTIONS AND METHODS
Python also offers many built-in functions and methods for list manipulation. You have already
worked with one such method len( ) in earlier chapters. In this chapter, you will learn about
many other built-in powerful list methods of Python used for list manipulation,
Every list object that you create in Python is actually an instance of List class (you need not do
anything specific for this; Python does it for you ~ you know builtin ). The list manipulation
methods that are being discussed below can be applied to list as per following syntax :
.()ee ee
COMPUTER SCIENCE WITH PYTHON .
{hth following examples, we are referring to latObject as List only (00 Telia eae
ape meaning is intact, you have to replace List with legal ist (citer alist itera or i
Object that holds alist),
‘et us now have a look at some useful built-in ist manipulation methods.
1. The index method
{tis function returns the index of frst matched item from the lst. Its used as per following
format ;
List. index (- )
For example, for a list L1 = (13, 18, 11, 16, 18, 14],
Pecaac tata (18 ) ec eee pela ey Aertel flees 6]
1 there i anoter vue 18 at nde 4
However, if the given item is not in the list, it raises exception value Error (see below)
List. index(33)
Traceback (most recent call last):
File “”, line 1, in
List. index(33)
Valuetrror: 33 1s not in List
2. The appéfid: method
As you have read earlier in section 7.4 that the append{ ) method adds an item to the end of the
list. It works as per following syntax :
List.append(
- )
~ Takes exactly one element and returns no value
For example, to add a new item “yellow” to a list containing colours , you may write :
>>> colours = [ ‘red, ‘green, ‘blue']
: (yellow
>>> colours. append(‘yellow) ee
>>> colours end of thelist
(rect, ‘green’, ‘blue’, 'yellow]
The append( ) does not return the new list, just modifies the original. To understand this,
consider the following example :
>>> Ast = 02, 2,3]. aiyine to ag the rer of
>>» 1st2 = 1st. append(12) stint ea aoa
>>> Ist ‘dd not return any value
(4, 2, 3, 12) «<——_ ur tise tt, on which append) wos
‘applied, has the newly added elementgoo UST MANIPULATION
4 The extend method
‘That is extend( ) takes a list as a
to the list object on which extend(
Consider following example ;
is applied,
moths [a,b,c]
pta=[d,'e]
a Pit th i 0 ing ot
>>> thextend(t2) ae
>tr ce of te
sl teen fe
[a,'0,'¢,'¢,'¢] woitine
>oot2
[¢,'e) PG te me
The above example left list t2 unmodified. Like append(), extend() also does not retum any value.
Consider following example :
Tong to eign the eof
>>> t3 = tl extend(t2) cere emmeteet
po ‘See, 15 is empty as extend) did not return ay value. But
Taye eked th elements of it 12.
Difference between append ) and extend )
While append{ ) function adds one element toa list, extend( ) can add multiple elements from a
list supplied to its argument. Consider the following example that will make it lear to you :
>ooti=[1, 3,5]
rte [781 npend) can take single objet ~
>>> tL append(1@) aE tohether ingle let or sngle sequence
doth
{4)3, 9740) Notice when we ny give male
>>> t1-append(12, 14) «~ arguments 0 append), what happens?
‘Traceback (most recent call last):
File “cpyshell#4>", line 1, in a
t1.append(12, 14) a a
Typeerror: append() takes exactly one argunent (2 given)244
COMPUTER SCIENCE WITH PYTHON .
2? tL append( 2; y es nthe
14] ) I i 19 eve ail cr
>> ta CED ‘fas of tt (atce gure brackas (})
1, 3,
(3,5, 10, (22, 14) <————— bgp tate comple i a ne emo
Check te Keng of th Ut, Hl sho that mow I
>>> Ten(t1) Solements, becuse newly adda st (12, 14] ts
s moat us sngle object.
es
>>> t2.extend(19) <———— ‘he te) comma wh se dae
Traceback (most recent call last):
File “", line 1, in «modules
t2.extend(10)
TypeError: ‘int’ object is not dterable
>>> t2.extend([12, 1)
>>> 2
17, 8, 12,18) ee f pend) cn a sage
>>> t3 = [28, 40] lement tothe end of alist while
at can 8 spunea
>> e2vextend(e3) « fats al elements tote end
>>> t2 (the tis.
(7, 8, 12, 14, 20, 40) Notice, extend ) added the individual ‘After append| ) the length ofthe
>>> len (£2) jt” element ofthe lit argument 13.12, Ist will Increase by 1 elemem
a "which earler hal 4 elements has now only after extend, the length
E-clements— including 2 elements of “af the list wl increase by the
tats, ‘Jenath of inserted lst.
Semomcsimmamnd
4. The insert method
The insert( ) method is also an insertion method for lists, ike append and extend methods,
However, both append( ) and extend{ ) insert the element(s) at the end of the list. If you want to
insert an element somewhere in between or any position of your choice, both append ) and
extend{ ) are of no use. For such a requirement insert) is used,
‘The insert() function inserts an item at a given position. It is used as per following syntax
List.insert( ,
- )
— Takes two arguments and returns no value.
The first argument is the index of the element before which the second argument
- is to be added.
Consider the following example:
>>> ths ['a, eu’)
>>> tleinsert(2, ' # inset element 'f’ at index 2.
>>> th
Ca, ef.) + see element inserted at index 2goon 7 UST MANILATION
Het Sah Fe ean sy ea,
List insert(@, x)
will insert elemen
List.insert( len(ay, x) . at the
If, however, indexis less than
(depends onthe sie of thelist theater Tel aPY ofthe vad negative indexes ofthe st
a list t1 = [2','e’, WL if we do: Prepended, ic., added in the beginning of list eg, for
>>> tl.insert(-9, «ky
[ky *a"
ae # valid negative indexes are -1, -2, -3, -4
# List prepended with element ‘k?
5, The pop method
List.pop() # cindex is optional argument:
~ Takes one optional argument and returns a value ~ the item being deleted
specified, pop( ) removes and returns the last item in the list. Consider some examp!
>>> th
(K, ‘a, ‘et, 'p,'¢,'U)
>>> elel = t1.pop(@) <——_ Rema elamen! tinder 0, ft
Thus, pop() removes an element from the given position in the list, and return it. If no index is
>>>elel demented sor in ela
KGB Wren deen
dott
[aye ‘Lf U] star vemog ft cement
>>> ele2 = t1.pop()
>>>elez +} io index specifi it il remove
Fe the lt element
pooth
[ae ‘2, Bd) i :
} method raises an exception(runtime error) ifthe ists already empty. Consider this:
The pop(
po t2=[] —
>>> t2.pop() pe ip ee fm
: exon,
Traceback (most recent call last): be
File “", Line 1, in
*2.pop()
IndexError: pop fromempty listi
a8
246
6. The remove method
el
it in advance
The remove( ) method
following format :
Uist renove ( )
The removes ) will report ane
>>> tle [a,‘e,
>>> tL remove(‘a!)
as
COMPUTER SCIENCE YATE PITH _
ile Pop() removes an el ion is given, what if you know the value
lement whose position is given, if you knov Of the
thought iin rt. But you donot know its index or position in thelist? Wel ye
ought
and made available the remove( ) method.
Temoves the first occurrence of given item from the list. It is used as pe
~ Takes one esental argument and does mot return anything
"Tor if there is no such item in the list. Consider some examples.
+ Pd, a, 'd,'p)
>>> ti 4 Frnt cccurence of ‘is removed fom the lst
Ces tp aya, %
>>> tl remove(‘p')
>>oth
>>> tL remove(t)
‘Traceback (most recent call last):
File “", line 1, in
‘t1.renove("k)
ValueError: list remove(x): xnot in list
7. The clear method
Toying to remove am element whichis
"ot present inthe Ui, rises ror.
This method removes all the items from the list and the list becomes ern
fon. This function
List.clear( )
returns nothing. It is used as per following format.
For instance, if you have a list Li as
>>> L1=[2, 3, 4, 5]
99> Ldclear() ¢___ it wit nemone all he items from Be 14.
>>>
‘Now the Lt is am empty list
et opr
Dnlike del statement, clear) removes only the elements and not the list element.
After clear(), the list object still exists as an empty list.
8. The count method
his function retums the count ofthe item that you passed as argument. If the given item is not
in the list, it returns zero. It is used as per following format : &
List. count(
- )
For instance, for a list L1 =[13, 18, 20, 10, 18, 23]
>>> L1-index [18]
2 >> L1-index(28)
0 vite with value 28 in thelist hence it returned 0 lero)«LST MANIPULATION
oot?
Put
4, Why ate USS called mutable typey 9
1 ac immutable counterparts a
vist ae afferent ways of cretng)
sts ? }
4. what values can we have ina is pol
they all have to be the same type 2
45 How are individual elements of ists are
accessed and changed ?
& How do you create the following lists ? ©
@ 54
@ 43)
© -5]
(@) [9 -10, ~11, ~12
@ (12
1, a= (5, 4, 3, 2, 1, 0) evaluate the
folowing expressions:
(@) afd)
(®) af-1)
(9 alalol)
@ alal-1)]
e) ala (a fa (2] +111)
8 Can you change an element of a
sequence? What if the sequence is a
string? What if the sequence isa list?
9. What does + b amounts to if aand b
ae lists ?
10. What does a * bamounts to if and b
ae lists ?
TL. What does a + bamounts to if ais alist
and b=52
12. Is a string the same as a list of
characters ?
18, Which functions can you use to add
elements to a list ?
‘4. What is the difference between append( )
and insert( ) methods of Uist? i
15. What is the difference between pop( )
and remove( ) methods of ti
3
16. What is the difference between append{ )
and extend( ) methods of Uist?
17. How does the sort() work? Give example.
18. “What does list. clear( )function do ?
21 PE
verses the items of the list. This is done
it does not create anew list. The syntax to
method is :
Ust.reverse()
9. The reverse method
The reverse ) rey
in place”, ic,
Use reverse
~ Takes no argument : :
it, returns ; 4 /
trl des not ae ee reverses the list ‘in place
For example,
ott
Cet, 4,2, '¢,'p]
>>> t1.reverse()
>ot >>tae[3, 4,5]
>>>t3 = t2. reverse)
dota
>oot2.
(5,4, 3]
<8 sores nating as reverse)
Ales not return anything.
10. The sort method
The sort() function sorts the items of the list, by default
in increasing order. This is done “in place”, ie,, it does
not create anew lis. Itis used as per following syntax:
List.sort()
For example,
roti=[e, ty ca
>>> th.sort()
pov th TT Sorte it in deft ascening order
Ca,"
Bt a
Like reverse(), sort() also performsits function and does
‘not return anything.
To sort a lst in decreasing order using sort( ), you can
write:
>»>List.sort reverse = True)
note, sort) wor't he able to sort the values of a
if contains a complex number as an element,
Python has no ordering relation defined for=
COMPUTER SCIENCE WITH PYTHON.
ogra (nd nt lemon ron tof element alongwith index In he
Ast = eval (input(“enter List : *))
Length « ten(1st)
min_ele = 1st[o]
min_index = @
for 4 inrange(1, Length-1) :
AF Ast[t] < minele:
minele = Ist[i]
min_index = i
Print("Given list is: ", Ist)
Print("The minimum elenent of the given list is :")
Print(min_ele, "at index”, min_index)
encershistiol2yi3ei4y 216s =F alas 1-9) 21)
] Given ist is : (2, 3, 4, -2, 6 7, 8, 11, -9, 12)
The minimum element of the given list is :
-9 at index 8
7.4 Program to calculate mean of a given list of numbers.
P ))
— Ast = eval (input (“Enter List
Jength = len(1st)
mean = sum= 0
for i inrange(@, length-1) :
sum += Ist[i]
mean = sum /length
print ("Given list is: ", Ist)
print("The mean of the given list is :", mean)
Enter list : (7, 23, -11, 55, 13.5, 20.05, -5.5)
Given list is : (7, 23, -11, 55, 13.5, 20.05, -5.5]
The mean of the given list is ; 15.364285714285714
7.5 Program to search for an element in a given list of numbers,
Ast = eval (input("Enter list :"))
Jength = len(1st)
element = int(input("Enter element to be searched for 2)
for i in range(@, length-1) :
ifelenent == Ist{i] :
print(element, “found at index”, i)
break
else: #else of for loop
print(elenent, "not found in given list")eo
ple
qwo sample runs of above Program
ate being given below :
ist : [2, 8, 9.
pter Vist ? (2, 8, 9, 42, 55
en elenent to be searched fop 22? 78: 67]
“41 found at index 5 Seah
Cen
enter Vist : (2, 8, 9, 11, 55
<1)
enter element to be searched for : mee 78, 67]
-22 not found in given list
? 7.6 — Program to count frequency of a Siven element in a list of numbers.
ogra!
= Ast = eval(input("Enter list :"))
length = len(1st)
element = int(input("Enter element :"))
count =@
for i in range(e, Jength-1):
if element == 1st[i}:
count += 1
if count ==@ :
print(element, “not found in given list")
else :
print(element, "has frequency as", count, "in given list")
Sample run of above program is given below :
Enter list : (1, 1, 1, 2, 2, 3, 4, 2, 2, 5, 5, 2, 2, 5]
Enter element : 2
2 has frequency as 6 in given list
249 Se,ver 7ST MANIPULATION,
cw
Type A: Shor! Answer Questions/Conceptual Ques
stions
Discuss the utilty and significance of
What do you understand. by mutability
9, 10}. Do the follow
(@) Set the second entry (index 1) to 17
(b) Add 4, 5 and 6 to the end of the lst
(©) Remove the first entry from the list
(@) Sort the list
{e) Double the list
(f) Insert 25 at index 3
4. Iais (1, 2,3)
(@) what is the difference (if any) between * 3 and (a, a a]?
() isa * 3 equivalent toa+a+a?
(©) what is the meaning of a[1:1] = 9?
(@) what's the difference between a{1:2} = 4 and aftst] = 4?
5, What's a [1:1] ifa is a string of at least two characters ? And what if string is shorter ?
6, What's the purpose of the del operator and pop method ? Try deleting a slice.
7, What does each of the following expressions evaluate to ? Suppose that L is the list
["These”, [“are”, “a”, “few", “words"], “that”, “we", “will”, “use”].
@ U(2}fe::2]
(b) “a” in L[1)[@]
(© Lf:2) +0[2]
(@) L[2::2]
© L(2}(2] in tf.)
8, What are list slices ? What for can you use them
‘9, Does the slice operator always produce a new list
10, Compare lists ei strings. How are they similar and how are they different ?
11, What do you understand by true copy of a list? How is it ditferent fom shallow copy a
es eerer ara reticent ai arrose Coa oe ee
sts, briefly,
“in place” memory updation mean ?
ing, using list functions :
255=. 256
Type B : Application Based Questions
1. What is the difference between following two expressions, if Ist is given as [1, 3, 5]
() Ast 3
(i) Ast +3,
2. Given two lists
tis ["this", ‘is, ‘a’, ‘List'], 12=["this", [ "is", “another"], “List"]
‘Which of the following expressions will cause an error and why ?
@ tret2 © L.uppert ) (9 L2[3]-upper( )
© L2upper¢ (© L2[A}.upper() L212] upper )
Krom the previous question, give output of expressions that do not result in error.
‘4. Given a list L1 = [3, 45, 12, 257, [2 1,0, 5, 88]
(@) Which list slice will return (12, 257, [2, 1, 0, 5]
(®) Which expression will return (2 1, 0, 5}
(©) Which list slice will return [2, 1, 0, 5}
(@ Which list stice will return [45, 257, 88)
5- Given a list Li = [3 45, 12, 257, 1, 0,5] 89), which function can change the list to:
@ 13,45, 12, 257, 88)
©) B45, 12, 257)
© (1, 1,0, 5} 88]
6. What will the following code result in?
l= [4, 3, 5,7, 9)
print (L1 == Li.reverse( ) )
print (12)
7. Predict the output
my_list=['p’, 'r', ‘0’, 'b', '1', ‘e", ‘m’]
my_list[2:3] = []
print(my_list)
y_Aist[2:5) = []
print(my_list)
8. Predict the output
List1 = (13, 18, 11, 16, 13, 18, 13]
print (List. index(18))
print(List1.count(18))
List. append(List1.count(13))
print(List1)
9. Predict the output
Odd =1,3,5
print( (Odd +[2, 4, 6])[4] )
print( (Odd +[12, 14, 16])[4] - (odd +{2, 4, 6])[4] )
10. Predict the output
a,b, ¢ = [4,2], (1, 2], [1, 2]
print(a == b)
print (a is b)
a
COMPUTER SCIENCE WITH PTHON — 11.
15.
Type
17 UST MANIPULATION
predict the output of followin
8 tWo parts, A;
@ W Le, 4
+14)
Be
aft] = 5 O 4, eat, 4)
ig terse
print(L3) Bates
Find the errors print(.3)
t= [1, 11, 21, 31]
ie=t142 i
us=la"2 |
Idx = L1index(4s) :
Find the errors
2 oe =) a ® uet
-remove(41) =u, 2,
Receesyy
Find the errors printan +2)
u-
° aio a © =, 3,8, 1,3, 0, 1, «0, 12°, fer, tw, fer, 4
tase Sree Cir PT RRM aaL eee
peine(a #38) point( Ui [-a: -2
print(L2) Seta nee
What will be the output of following code ?
x= (3, '2,'5]
eae
while x :
peered eT
x=x [1 len(x) -2]
print (y)
print (x)
print (type(x), type(y))
31)
3:-4))
C : Programming Practice/Knowledge based Questions
Write a program that reverses an array of integers (in place),
‘Write a program that inputs two lists and creates a third, that contain all elements of the first followed
by all elements of the second.
‘Ask the user to enter a list containing nu
list that are greater than 10 with 10.
‘Ask the user to enter a lst of strings. Create a new list that cor
characters removed.
Create the following lists using a for loop =
(@) A List consisting of the integers 0 through 49.
(b) A llist containing the squares of the integers 1 through 50. :
(@) The list [a /bb'/cce’/ddda’, .. . | that ends with 26 copies of the letter z.
dee at ke ny oro as ana a of amt ad 8 a
form a new list N whose elements are sums of the ‘corresponding elements in Land M. For instance, if
L=[3,1,4] and M=[1,
bers between 1 and 12. Then replace all of the entries in the
sists of those strings with their first
5,9) then N should equal (4/6131.COMPUTER SCIENCE WITH PYTHON _
7. Write a progr . Fi index moves to the
ee eer ee aoe ae eee
‘Moves to the first index
®: Write a program that reads the » to display nth term of Fibonacci series.
‘The Flbonacei sequence works as follows :
* element 0 has the value 0
* element 1 has the value 1
‘every element after that has the value ofthe sum of the two preceding elements
‘The beginning of the sequence looks like :
0,1,1, 2,3, 5,8, 13, 21, 34,..
n, Program prompts for an element and prints out the value of that element of the Fibonacci sequence,
wus :
* input 7, produces 13
* input 9, produces 34
Hints.
* Don’t try to just type out the entire lst. It gets big very fast. Element 25 is 75205. Element 100
'354224848179261915075. So keep upper limit of n to 20.
°. Write programs as per following specifications
(@) ** * Return the length of the longest
string in the list of strings str_list.
Precondition : the 1ist will contain
at least one elenent.‘"*
(®) *"' Lis a list of nunbers. Return a new list where each elenent is the
corresponding elenent of list L summed with number num.'**