0% found this document useful (0 votes)
16 views8 pages

Adobe Scan 15-Dec-2023

The document explains various operations on lists in Python, including replication using the * operator, comparison of lists, slicing, and adding new elements with append(), extend(), and insert() functions. It also covers modifying existing values, removing elements with the remove() function, and provides examples for each operation. The content is aimed at helping users understand how to manipulate lists effectively in Python programming.

Uploaded by

Jyotsna Pahwa
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)
16 views8 pages

Adobe Scan 15-Dec-2023

The document explains various operations on lists in Python, including replication using the * operator, comparison of lists, slicing, and adding new elements with append(), extend(), and insert() functions. It also covers modifying existing values, removing elements with the remove() function, and provides examples for each operation. The content is aimed at helping users understand how to manipulate lists effectively in Python programming.

Uploaded by

Jyotsna Pahwa
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/ 8

l I II I .

', \ I 11 , ), J, 4, S, b, 7, 8, 9]
l { I 1 1 :l, ,, I
111 '\\' l i ·l I l l t t •1 , ,, , (\ I t I ~

! 'l i I\ I I n t> W I l !, t )

Using * Qperator-with-l-ist-- I

l ht' " t'Pt't ,1h"H b usNi to n'plic,1te n list by n specific nurnber of times. With * operator, one operand has to be a ;
h~t ,rnd tlw otlw, should only be nn intege,~ otherwise it will give an error. For example,

Commands Output
A 11, 2 , J) [1, 2, 3, 1, 2, 3, 1, 2, 3]

pri nt(H )

X [S, 5, S]
A [X] " 3

p r i n t (A)
Commands Output
n a me " Amit " ('Amit', 'Amit', 'Amit', 'Amit']
Ll [na me ) " 4
prin t (Ll )

name= "Amit" TypeError: can't multiply sequence by non-int of type 'str'


Ll = [name ) *
II a II

Comparing the Lists


The comparison of the lists is done using comparison operators >, <, >=, <=, != and ==. These operators
compare the elements in lexicographical order. For example, if corresponding elements are same, it goes to the
next element, and so on until it finds elements that differ. For example,
11 = [ 1, 2, 3)
12 = [ 1, 2, 3)
13 = [ 1, 2, l 3JJ
14 = [l. 0, 2. 0, 3,0)
print(ll == 12) #True
print(ll > 12) #False
print(ll == 13) #False
pdnt (11 .... 14) #False
print ( [1, 2, 6) < [ 1, 2, 5) ) #False

~ ' 312 \ Touchpad Artificial Intelligence-IX

'''''
a as
1 ct J . . I a

n,•,1 • n
41fds- \ti
print([l, 2, b) !• 11 , 2 , 5) ) #Teue
pi-int { [l, 2, G) ' [l , 2, 5) ) #True

slicing a List
, 1. a list means_accessing a spe:ific portion of a list. This can be done by using a range of values with start
19
e\ number, end index number with colon in between. We can use both forward index and backward indeY t o
c::cify the range of slicing a list. Some important points to consider to do slicing in a list are:
, Elements from beginning to a range - list[: index] or [ : -index]
, Elernents from specific Index till the end - list[index:]
, Elernents within a range - list[start index: end index]
, Elements within range using step value - list[start index : end index: step value]
, Whole list in forward order- list[: ]
, Whole list in reverse order - list[:: -1].

For example,
word = ['E ' , 'D' , 'U' , 'C' , 'A' , 'T ' , ' I ' , '0 ' , 'N' l

0 1 2 3 4 5 6 7 8

E D u C A T I 0 N

-9 -8 -7 -6 -5 -4 -3 -2 -1~ •ckward - ~
,~c
I

Commands Output
Examples
word [ : J ['E', 'D', 'U', 'C', 'A', 'T', 'I', 'O', 'N ']
To display the whole list
or
word [ : : ]

or
word [ 0 : ]

or
word(-9:]
Displays the alternate elements print (word [: : 2 ) ['E', 'U', 'A', 'I', 'N']

of the given list


['E', ' D', 'U']
To display ['E', ' D', 'U'] from the word [ 0: 3 J
above list or
word[ :3]

or
word[-9 : -6)

Ol

word [: -6 J

Introduction to Python
__I 313 __.;:..:,.;._--
•~· ' T'j frc-.m tne .'C · ~•. T j

To c ·sn a:. ~O T. TJ ~:"" :he


a ::xr. e is.:

To a'spla, the ''st;., reverse oroer ,.a:::-~. : : - 11 ['N'. ·o·. ·r. ,·. 'A ', ·c·. ·u·. ·o·. ' E1

a Task
!f word = ['E', ' D 'U 'C' 'A' T 'I' 'O' 'N')
What will be the output of the fo!lo'lt 1ng !'1Structions·
• print(word[:1:-2])
• print(word[-1:H
• print(word[:-11}
---~-~---------~----~~- -------------=-~
Adding New Elements to a List
There are three different functions used to add elements in an existing list which are appe:;d < },
ex.:.e.:1d ( and i.!!serr. , J • Let us learn about them in detail.

The append{) Function


The appe!!ci' Function appends a single element with the given value(any datatype) at the end of tre ·~
We use this fundion m a loop for adding multiple elements. With the single append ! . function, the eng
of the list will increase by 1. Syntax of the append ( ) function is:
lisL . append(ir.em}

••
"'ll'
314 I Touchpad Artificial Intelligence-IX
J

• fl ~ I I I ' I 111 t, e 111, y v11 1!1tl


ltl " 1,1111,l,uf, ti lll1tlf I IHH , 1111 l h Htlfrlt"
!f
ii(
ltf il ,
o/1 (otntllfth(l6
Ovtr•ut
tr td I i
11 1 I, , 1 I
" I f'1 11 ,, ,t ', 11 1,ni ,m, ,
1
,
11
111{111 IP , "r·riPl(,11 'I
il f'I'' 11 11 ( "r11t f ( 1/1 II)
t I 11 l t: ,

I (f I " iI j )
f'' I fl
, .. ,,,,, 'Ill l II' "1 r,, rl" I 11
t;f1l 1 Rf 1; l''tA ir11ll", •fl,1<1", "J l< •11tl , 111 H / 1111dnl J
ei,r:' , l:l l•l't 11 r.f ("ll1,11 r.ln" J

I
"' fl,,,
ij( ' "
,t1 II' I( II II 'I I l '' ( I ' 1 If )

rr j II I ( r.• 1 f fi )

#J1,p1JI /1 {1 ffll I ,,1 ', 1d 111 ,n I I II I 11 l I I (11lor I rlt11d tltm,o Ar;"I


f I I f• 11 rl Il rnt,,r I rltmcf I\Jnrn • (,11t1hfi
tlJc l l n , 111qt (',): ( 11tm rrit nll Nnrf,c· ,Wall
111111111,u1("J.n1 r lr1,ricJ !Jim s "l l ntr:r rrlM1d tJ m10 '-uc11,,,
I, le 11dn. ff'I" 11r.l (r1111) [11tor f rl ·ntl N 1J11 '•hli hf
1,1111l (frl11r1d t ) ("t,rn,t , ,fl h, , ,w ,ti"," ,udhtr", ·•<,ho '11"1
H

#r,1ddir1'1 ll ll I !'i f th 11 I Of II O, r bhlt, ('tlr, ,', 'hcm'II


1, t [', t ', 'd J(J ' , ' r I ,bl 1 ' J

•,tj lrl [ 'tJ q, r' , ' J S c,r,' I


P tB . 1J,f1( n J(w i Id)
r,rint(p•l)

The extend( ) Function


Th,, (jz t t•nd () I Wl< lion i,; ua;cd tc, t1ppm1d multipl Synt ,x of tho cztcnd() f unc.tk,n tr.:
+-
.d . t,, x t, n d ( 1 t t t hl v l u}
¥ihere itP.rablc value can bfl a lli'it Example nr •

Command• Output

Tl [ 1, 2 , , 4I (1, 2, 3, 4, SJ
m [ ]
n. X\ n (m>
print (n)

t. ( I t •' , r.t '.4 1 , ('cat', 'dog', 'rabbit', 'tiger·, 11io n'I


I
f
bl, I I
w d ('l J I

I d(W ct)

~r , (p

lritrodYttron tc, Python j )1~ :,,


The lnst,rt( ) flunctlon
It\\~ ,r1 ~) \ \ \ h111itll'll,l'>\li.~dl\',llld~i.ll1Ul~\'~1h1t> I\ 1 ~11\:'lltll l'I' llt1111h1 IIIV!\l"lt\\jl\,\ lhi•l1c,\\lt\h 11
,1 '-'111;
11,, \\ 1ll 1n1 tt\ 1,~ t-, Pllf\ ~, nh1, N 1hi• 111 .~, 1 1 1 htlh 111 11111i,
l I l , \n ~I l (ll11l~~ 1 \ v"lll\i)

l \\i111plex:

o,,,1"•\
l, I l \) I • () I ll (I HI '\ I \\II
I, , ( 11 ('\ I l (~ f

I\\ l Ill (I,)

I I l i II t ( 1,}
a 11 ~ \' II

l'lilll\L)

l. im,r.1 1 ( 11 1 I "a 11 , 11 t•" I) ('"tic:\ ll> 40 1 \) l:' ,O I'('\ 't,'I, ~01


ptl11t(L)

Modifying Existing Values In n List


Ltst ts rnut«blr so dc1tc1 c,1n bt• t',1,1h 11\\hhfied b, o, "' ,H1tl110 n new Villue tc, \I\ t,\ Mt111 , , .,,m, 111 {I (ll\'NI H,t t,,
u,inq «n n<:s.1qnmrnt oprt ,1t()I ( ) '-v11t.1x to 111od11\ \•,ls.Ung ~aluc;s. m n lh,t ,~
l i. ~: t [ :i nch'x J • l\P\\'V,1 l \It\

Exnmptr:

Commands Output
11•118 1 '0,40, ri()J JlO '0. 40 100)
lL[q •l OO
p1i11t(ll}
l l I l: ~J l " ab..;'',"~) "l / (10 ·i,bc' ·~y1.' 1001
p1int(ll) V
Removing Elements from a List
l he1e me two difter('nt tunctions u-.ect t\) rern1.J~~ d~n,ent, in cm t,:~htln1.J 11-.t t m ~, , ( ~ ctl\d \ • )l' ( ) lt,.t ' '
lcc11 n nbout thes(' function, m dt't,1il.

The remove( ) Function


r he .. ('m<we- \ > tunct1011 tt'mov~s th~ fit ~t O\".C'U11t'11c:e of th~ ~lernt•nt wtth tht• i<pt-~fmd \.\httl-.. lt t\\t"-"m t:
one value c.nn b(;\ rti-mowd ,,t ,t turn• t'V~'" if th~re are duµlk(lte vah1t,s m the h~t lf )t'\I ,~lsh t<l ~m ,,-em, tt ·
values then thi<: f1.1nttion \.M\ be ust"d within n 101.,µ wh~re 1t 1rpi',1t~ lht-lf n -.p~dfic munb~, (1f \Im ·~ ~ it~' '
the · .:-movt~ \ l function ,~:

~ ' 316 j l0L1chp_"ld At tifk1al l11tellt9~1\1.~ l\


lfti'",,,,, • -~ . -- • • _ . , _. . ..,.f V" ~•' ,._'i

,,
,)

remove ( < s i n gle v alue> )


1ist .
xarnple,
for e
Commands
marks• [23 , 34 , 23 , 45 , Output
56 , 7 8, 56)
mai:ks . remove ( 23 ) marks • (34, 23, ,1s, SG, 18, 561
print(marks )
mai·ks . remov e ( 56)
marks = (34, 23, 45, 78, 56)
print (marks)
mar k s .remove(72)
ValueError: list.remove(x). x not m hst
The pop() Function
The pop c } functio n removes an ele~ent from the list based on the index number specified in the function and
turns the deleted value. In case no index number is given t hen by default it removes the last element from the
IS • If we try to rem ove an index number which does not exist then it gives an I ndexError. For example,
ret
Commands
Output
vowels=[ ' a ', ' e ', ' i ', ' o ', 'u' J 'i'
val=vowels . pop ( 2 )
print(val }
val=vowels . pop () 'u'
print (val)
val=vowels . pop (6) IndexError: pop index out of range
print (val )
1st= [ J IndexError: pop from empty list
1st . pop ()

Some other Functions Used with List


There are some other functions also available to use with the list which are as follows:
' lenQ: l ~.f.unction returns the length g.f a list. For e~ple,
marks "" (1 0 34 42 21 45]
. , , ' ' /
Pri nt(len(rnarks }}
Output Will be 5 .

e>(1st5 : Thi
' clearo• f .
-L,_unct1on removes a 11 t he e Iements of the list in..one-go. It empties the list but the empty hst still
in Python which can be used later to fill the values. For examp 1e,
City"' [ " Delhi ", " Mumba i", "Ko lkata", " Ch e nnai " J
City
· Clear ( )
Pt ·
J.nt (c ity)
' OlJtplJt Will be· []
te" .
1 erseo: This function reverses the content of the list "in place". For example,
~ Ph r -
Cl "' [ I
<1lI-ih a ' , ,b , , , c , , , d , , , e , J


<l • tev
e.tsp ()

Introduct io n to Python I 317 , . ,

/
prin t (alpha)
, ' 'd' 'c' 'b' 'a']
Output will be: [ e' ' ' ' h' · d ... th I' t ·t If" d
. sorts t he rist ·in ascending or descending order. T 1s 1s one m e 1s I se an works for
• sort(): This function
the list with values of the same data types. For example,

city=[ "Delhi " , "Mumbai", "Kolkata", "Chennai"]


city.sort() #sorts the list by default in ascending order
print (city)
Output will be: ("Chennai", "Delhi ", "Kolkata", "Mumbai"]

city . sort(reverse=True)#sorts the list descending order

_________________ -
Output will be: ["Mumbai", "Kolkata ", "Delhi", "Chennai"]
• indexO: It....____
returns the index number of the value given in t he function. For example,
city=[ " Delhi ", "Mumbai ", "Kolkata " , "Chennai"]
city . index ( "Kolkata " )
Output will be: 2
city.i ndex( "Pune ") c9'
Output will be: ValueError

It returns ValueError exception if the value is not fo und in the list.

• countO: This function counts the number of occurrences of the specified value in the given list. If the value
doesn't exist, then the function returns 0. For example,

marks = [56 , 67 , 45 , 78 , 56 , 78, 12]


marks . count (78 )
Output will be: 2
marks. count (l O)
Output will be: 0 # 10 does not exist in t he list.

9 Ato Glonccz
• A program is written in any programming language which the computer can understand and execute.
• Control structures are a set of instructions that controls the flow of instructions in a program.
• An algorithm is a step-by-step approach to identify and solve a problem in a finite time.
• A flowchart is a graphical representation of an algorithm.
• Python is a general-purpose, object oriented, easy to learn and high-level programming language.
• Instructions written in a source code that are executed by a Python interpreter are called statements.
• Tokens are the smallest meaningful unit of a program.
• Identifiers are the user defined names of variables, list, dictionary, tuples, classes etc.
• Variable is a name given to a memory location to hold a specific value.
• List is a collection of heterogeneous data arranged in a sequence.
• The elements of a list can be accessed by using its index number starts with o (zero).
• The + operator is used to concatenate the list with another list
• The * operator is used to replicate a list specific number of times.
• The comparison of the lists is done using comparison operators>, <, >=, <=, !=and==.
• The append( ) Function appends a single element with the given value(any datatype) at the end of the list

••
~~'
318 I Touchpad Artificial Intelligence-IX
,,,,,

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