0% found this document useful (0 votes)
3 views11 pages

Python 4

The document provides a comprehensive guide on creating and manipulating lists in Python, including methods for list creation, adding and removing items, and using loops for iteration. It covers various techniques such as hard-coding lists, using the split method, and applying range functions. Additionally, it discusses error handling and includes a project example for calculating a final bill based on user input prices.
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)
3 views11 pages

Python 4

The document provides a comprehensive guide on creating and manipulating lists in Python, including methods for list creation, adding and removing items, and using loops for iteration. It covers various techniques such as hard-coding lists, using the split method, and applying range functions. Additionally, it discusses error handling and includes a project example for calculating a final bill based on user input prices.
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/ 11

Usts

to store collectiorm of
"A list
in Python i5a way
items
te a list you ase the sguare byacke t C]
"To cYea
Outtome
Eg 1# Greate a playlist
2 playlist= [ vay'shubamulu
3" Vayishubaulu' Love i th the
4' Love wth the shape of you' Shape oE You'isey
5Hey Jude
Happy evening Ju de
let it Be Respected
8Joining &as
9 Dk my dear b Sis3
lo Respected si
11

q6t
prine (playlist)
ist can soievarious
s data types, mixed
data tyPes
"A list can Contain
a nestd is t
anotheslistThi s is (alled

SUst reatiorn methód S


"Ihese ase
mulbiple woys to reate a list
tHard-co ded; Use thts method when yo alread y know
the values that ill be in the list
1splt +(): Use this functon hen yo want to crQate
a list from
string
S Tange(): Use shen you wan
t Creote a
te Yangefunction
Stquence of nunbrs
Hard Coing a Ust:
" To crea te a list oith spe cifie values you alrea dg
knou use suaxe bracke tslJ and pl ace ech value
inside these sq uare bracke ts Sepero ted by cômm as.

Code 0utput:
1nunbers_list:
2print(numbers li'st)
9Splt( Method:e
"To transform a strin into a ist in Py thon, use the
stsing splht method This method divides the string base d
On
speciied sepera tor an dthen pu t S these
SmalleY par ts into tist.
"For in stonce consrdex the
string ,2, 3 To convey t
it into a ist 33 si mply use thepi4 me tho d
I, 2,3 spli t()
Thìs method sepesa tes the
String at
ever y comma.
Code!
output'
2: num beys s t = num bess_str.spli
t()
3' pri( numbers_ l's t)

TsansfoYming user input into a li3 t!


" Dse Pgthon's input 0 function and
the spl' t()
method to do th's
Code:
1:usesinput = input"Entey
items
2user- list = serinpu topl()separa ted by commas:)
3 Prtat (userIist ) n
Output:
items Sepevated by Commas , 2
inter

More Sepera torS;

-Comma: ,,3' spl' 4(',) divides at Com mag


Yesulbn
in ( , ,
" Dash Bsing;2-33pli the string s spli t at
dashes, giving , ,
Spate : IP have

y thon spli ts the string


Capple;banana cherry" split()
at space s, making
ist fopple' banana,
'eherry].
ist of Num bers:
rangel)
" her range()
function lo Pyth on
Sequence that begins produces a
ends usi be fore
komastarti ng QumbeY and
Speci fied stop num be
Co de!

1. Tange- obj= onge(,4) Output)


2" print (range. obj)
vange (i, )
Code!

JnumberS ist (range ()) Output:


1 print(numbess)
Step Parameter i
Fo exampte
Starts using range , lo,2),:
and
the seg uence
2 between
Stops at oi th a gap
ach of
numbe Y. 2 in Case the
Step parameter in thìs Yange function.
Code!
Ou tput :
1inumbes. '3t = li'st (range(1,Io, ))
2 print (numberti's t)
The step parameter controls the gap
'be toeen eoch
SuccessiNe element in the range

Indexing Syntax
. To get
Speefe item "honn a tis
ti6t, you
two thing ,the home of the (is t
and the'
jndet number
the lis t e ach item
numbe Star tng trom
isassianed an index
" The inde
number ts
itens less than the
positi'on in the ists2
Code:
Output!
1.myist=fa,
2-prlnt ( my
isto)
" An ndez ErToY 0cCurS when
acceSS Qn inde number that is
ls t's rangc the

Negative Indexing:
"Lt is usetul hen you wan t to get i temg from
the end the is!
’ Thelast ite m i5 accessed
using list _iname
second last item a ccessed using
is tname 2), and So

Output:

2 print (my_list -a)


Adding Items to List!
. The Py thon hase Seveal me thods to d
item s
1'append () A neu tern at the cnd
2"insert()Add a he w Lte m Qt
spe efc adex
Ehe sti's
3 extend):A d
lmuttipleitems at the end of
the

APPend method:
Code!
Dutput!
my-lista
2 my- U's t
app ent
3 print (myis)

Insert method!
Code!
Output.!

2my'st. insert(1, b)
3 prin
(my ist)
I you in ser t ar i te m at an index beyond
the
The ite ist's
m 5i2e, Py thon won an ero
was adde d to Bhe e nd f the li's &
Extend method!
Code! butput!

Imylist d, }
2 myist. extend
(CU)

Remouing Items!

"Python provides Severa methods to


Yemove listitem
1 popO: Delete s ar item at a specific
inder.
2-Temovel):Remove s the firstoCcUrence of
3 clear():
Empties the lis t of all item
value

Pop Method
Code!
Outpu t!
1mylrst'a, b4,
2- my-listo pop(2)
3· prìnt(my. list)
the index i5 Out of
thoow an Indez Error Yanger Python o wil
Remove Method:
Code! Output
1-my-li'st a;]
2my-1ist. remove ('b)
B" prin t(my lis)
Sheuld
heeave tuoo pvimary

J. Valtie Eror Non Existenttems


for

Flrs t Decuvence onl4


Code

eValue error: istndex(a)


2 myst remove () ao otin tist on line 2

Code : Ou tpu t!

2- myList.emove (2)
opelnt Cmy.List)
Clear Method!
Codeico

2 my-is t clear()
3 print (m9-list)

Updotin9 ist
. To reaplae an item
in alist ,
a ne value to t 4ou a ssgn
at its specific index. Simply
Syntax
mylist Cinde 'nevalee' Otputi
Sode
2. my
3 print
we put index that doesn't exist t
Qn index eroY

Loops:
.When tasks in code are repetitive, i t's of ben
a sign that loopS Can be used to Sinnplify and
optimise the code
"There mainlg tuso types oP löDps in Python:
or loops Commonly used sith list s and used
when the repetition count s koon
’While lbops Conmonly used when
Yepetitionis
bosed a condit on and
anndwe
don't know thne exact repetition count

For lodp
.A or lDop
in Python goes
throug h each item
a list one by one, perfoY ming an
each then. actono7th
Code:
1· letters Outputi
2- to b,c.J
le tter tn lettxs
3:
printyette)
" Hexe
letteracts temporory variable
for each item in list
Indentation or Space betore we wri E Code
insl de the foY btd Ck is Crut al os indica tes the
s Cope in
Adding G'st Numbers:

Step1: Create a variable to hold the


i tens
" Step2 Crea te a for loep to go Broug h each ist iteo
Step 3: Add the value of each i tem to the Sm variable
as theloop goe3 thyoug h eachi tem.
Step y Priat the value of the sum variable after tha
loop ends

Code!
11tems 6utput
t, 22, 33)
The sum of al|.
2item-sum= 0
ite ms is 66.
3for item in i tems
tem Sum : item sum
+item.
4 print( the sum of at
item sis iem_süm3)
Alternative method! Sum(J- Funiton
Py thon proides a buil tin tunction
findthe Sum called sum() to
all tem in a
list
Code: à
1 iterns ",2, 33) Output!
^ The Sum of,al tems S
item.Sum= Sum (items) 66
3 print (4"The sum -offall iterm s is $i )
tem
While ops
The Ioop storts si th the
" The cond iti on
keyood hile"
ensures the code in side the
*uns epeatedly as loeng as a specific hile loop
isnt
"Jp the Condi bon,
Conditon i5 met
me t the lbop Stops
Indentatisn(using y spaces) is impor t an t
We con use the wshile loop to print sequon ce of numbers
Code! Otput:
1number o
2 shile number < 9
3 print (number)
number= number +!

This too is inside the IooP, increase te number


by
1 with each oop vepebtbo.
" We can als0 pint numbers in teverse order
Code:

1numbes9
2. while numbeY >o
diyprint (number)
Ynumbers number-I
(wspaa)
GAessing a nunber singi Pyth onKáame)!
1" 5eret-number This is the secret numbes which the
user has to guess to win the geme.

2 guess.number The ser's current guess. IP matches


the seCret. nunm ber, thé use win s! Otherwi'se, the
User hee ds to guesS again.
Code :

2 9uess-numbes int (nput (aue ss betyeen tand lo:" )


3" ohile gues
numbe Y Secre t number :
guess.number intlinput (huess
'auess be
be tue
tueen tand to)
Output!
Guess between and lo S
Guess be tusee n

Ghuess betueen and l0!

Correct!
The cshile loop en 3ures tontinuously, only brea king shtn
the coYYet conditior is satisied

(Project
E-Commer ce Hnal Bill Calaula tes

Designing progr am thot Qs t the 4ser to input


he produet prices, seperated bY CommQ S. Basedon their
di'splag the final bill by Summ in 3 up these prices.
Code
lprodat.
1 price-input input (En ter prices
2· produet- prices = pice-input, seperated by comm ag
split() du
3 fnal_bill o
4 tor price in
product - prices
tinal_bill= Hnal_bi)l + ioa t
(pri ce)
s print G me inal
bill :$6nalbill3
Ou tput:

Eenter pries
Seperated by comas ; 10,
The tinal bill:12.0 22, 4S

You might also like