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

Book Dec 04, 2024

The document provides an overview of tuples in Python, explaining their characteristics such as immutability, the ability to hold heterogeneous data types, and how they differ from lists. It covers tuple creation, indexing, and common operations like concatenation and repetition. Additionally, it emphasizes the read-only nature of tuples and their efficiency in storing data that does not require modification.

Uploaded by

aryanmudgal330
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 views25 pages

Book Dec 04, 2024

The document provides an overview of tuples in Python, explaining their characteristics such as immutability, the ability to hold heterogeneous data types, and how they differ from lists. It covers tuple creation, indexing, and common operations like concatenation and repetition. Additionally, it emphasizes the read-only nature of tuples and their efficiency in storing data that does not require modification.

Uploaded by

aryanmudgal330
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/ 25

12 TUPLES

qu I d t.l t p thc1t
I I
v p 11 11 d hy com l'll1lat
in Hg 9 3
n1.is IJ111 1ktl'I I
eI

tuple()

Fig. 9.3: A Tuple 1n Python

re called its lemrnts Tuples c11lows duphcdte v 1


,1 lJes 11
· 'eltie.,
type they can he heterogcncou,;, , r, of differe111 data ,,
r th omm sep 1rc1tl'd sequence of values d t;, 11
ecl,iteu
ll~lng
lu 1 • • • • V d .L u
n l

we have d tuple named 'Fruits', with three clements as ,v1c1ngo


l•. A
ment 111 a tuple are addressed using the11 111dex value. The IIHI ' PPle
ex Value or

d1 , nee betw en hsts and tuples are: Lists ,ire enclosed withi
n squar
.and their elements and size can be changed, while tuples a1 c enclosed e
wnh,n
( ) nd cannot be updated Tuple-. can be thoug I1t of as read-only lists.
u ble , e we cannot change the elements of a tuple in place. This ineans We
rm m ert update and delete operatlons on them. That 1s why tuples •ate faster
nt than hsts

uh~ but mt!m~r obJect~ may be mutable

EumpJ 1

. . . . . Hal,
f59c0932bf, tur 29 2018, 16:07:46) (MSC v .1900 32 bi

• or •11cen~•<>• tor mor information


l'i a comma ep rat d II t rval
I I I I I I I I t I
I I

I I

lie co111Pme'i a !ltngle element, the el mrnt ho Id


IJ tlll cd 1,y c1 1.,ommd to d1 ltngui,h a tupl e fr m ,1
I 110W pit
1 be fo izcd cxpr l'.Ss1on.
c11thCS Ide ,ty
par vinga~111glcelement1sal oknowna sin"' to
It' 11a .-e n df tt.d
Att111
1
tllP1eies bein g immutable, an attempt t modlfy an element of a tuple yields an ,rror, °
11.1P in r,ig. 9.4.
I 11own fi tup,110,2,
3S S ,401
I;» t~pl21•100

» tupl•l10,20,l0,40,14,:l,61J
>» tupl( 4II 11 •SOO
>>> t.ipl
no, 20. 30, 40, 14, so, i11

l
)))

Fig. 9.4: Modifying a Tuple Element Generate\ an Error

mutable but tuple 1s immutable So, iterating through a tuple 15 fHter ,s compared to I I t
c1'.a,ust
"' ,sdata that 1s not require d to be changed, then storing this data 1n • tuple will ensure thlt t
t,ave
r..vt ed acc1denta 1ly.
~otctian9 -~~~--
1\1'
. an clement ol a tuple is of mutable type, e!/, a hst, then we can modify that element
"owl'VCI, I
1

TUPLE CREATION
g,3 . enclosed in parentheses/round brackets ( J for c:1 eatwn and each item ,s separatedbY
Atuple is Round brackets indicate the start and end of the tuple. 1 he syntax to create a rupIe I
acomma.
syntax: Tup=()
Tup =(value 1, value2 ......... value n)

For example,
•upl {'compsc', 'infoprdcticc-s', 2::!I, .O ~,
, uP'- ,. ( 1 , 11 , .: 2 , 4 4 )
The above construct is known as tuple display construct.
1 ruo:e w1 th mixed da tel • ypes
>'> 'IIY tupl (l, "He.lo", 1 .4)
>'> print (1cy ~up
,, 'Hello', j,4)

ltuplehav.n s•r.nJw
•hi +-1ip ('dpplE ', 'b n,ni', ' t •r ')
> Pnnt(th1stJr::e)
,, pi,.e', 't r, ', 'crerry')

CTM: Indexing of tuple 1s Just like indexing of hst


pty t pl u n1 fun t on tuple( J

n nln1 ln,c v.1lu u mg function tuple()

h don 1th
,.,,..
, ~ ...... ~ e,-.
.,... .~ 1vJ,6.,
rr-""' 4, Ki
,2
rlqflt•, • rt11 •· r • f Ii:. t f

I
--- ------
r J
1
Pl TllTI

I
, I

lrt1Plcm1:ntatt0n 2
1Cd I
bovc program using/or loop
•~1fY thr a
L. ,...,.J.,., ( ~lt,,,.,.J,,JI_ C )(
f,lt Uil , _ __. ..., o,,c- fl-. tw,
t•
n•

IC.

j ,,..w Yloll
,,. ~ Sul OG,.,w ~ - liq
pythc.n 3,6.5 (v3.t.5:f5~c0~32b4, Hat 2e 2C18, :tf:C,7:4£1 lNS w.u 2
lll on \/in32
Typt •copyright~, •credit~• or •11c1n•t(l" tor IIGre 1 f rut1

.-••••••••••••••••••• RESTART: C•/Ch1pttr 8/pr911_2.py •••--•--------•--•


toter ,rny r. r: ,
Enter Numbe .. : 50
tr.ter fl 20
r I 8
r I, 100
ut h
•, '2u', ' 1 1 G' I
111blned to form a new tupt
e ••tu
111111ect1 n a tuple

C )(

))

- C l<

[MSC V, 1900 32 bit IIntt

r I p191_3.py ••••·•••·••••·••••••-

'l'Nnch')

LIi w c.e,
11 11
t I n
ri1PI
to ere

,lt(i) 11),
,It

. u,er~/preeti/AppData/LocaU
1" C• 1
~,(C,1 ' N Harle
fY pfP. l 1 t1° Harm t e
00 oe p ka 98
Ol Radhika 78
20" shaurya 90
.,04

Access1NG AND TRAVERSING ATUPLE


95,. ,~ a scqul'nce of values which can be of any typ and th y
\ 111Plc 1,1kC IJslS, Lhet e could be pos11tve indexing like 0, 1 2 3 or ne at an
~er
! 11 J ,.., ctC,
2,
2
0 3 4 5
' 7 I
'°""" ...

-~--
10 20 30 40 50 60 70 IO ,0

tuple/
-9 -8 -7 ·6 -5 ·4 -3 -2 -1

du,il elellll'llt::. of a tuple can be accessed through their indexes g v n


10J1VI •.
'fhe s shown in l•1g. 9.5.
rackets a
D of Otuple can he .iccesscd us111g an indexing method
Elernents
·ndices start at O.
fupIe 1
e index must be .1 positive or negative mteger value or .in expression wh ch e
"hetupl
egcr value. Positive value of index means counting forward from begmn ng ft tuple
10 an in l
and negative value means counting backward from end of the tuple

Filt ldrt Shtl 0t'"'9 ~ W,._ IWp


Python 3.6.5 (v3.6.5:f~9c0932b4, Mir 28 2018, 16:07:
46) (MSC v .1900 32 bit Until)] on w1n32
Type "copyright", "credits• or "lic1n&111• tor aore
tl•(l0,20,30,40,50,60,70,80,90)
tl(O)

tl[S)

tl(-5)

Fig. 9.5: Accessing a Tuple El ment


eacll eleaent or a tuple one after the 0 th
,......,. orwltl•loop er •tu..
l. ...........rtll ...........
.,_. loop Iterate, each element of a tuple in seq
uenc, '
n
In die llaow pl'Olhirn. the loop variable '1' shall be assigned the tuple elements
The loop ...-table 'f will be assigned 'p' in the first 1terat1on and, hence . , one ata tirn
' P gets e
dart, nth second iteration, 'y' gets accessed and printed. This proce ss cont Printed
1
all die elements of the tuple 'tup' are accessed and displayed. nuest,1l

.,.... raaae(J flllldlon


Ulce II tuples also can be created using range(J function .

..
.__ _ _ _ _ _ _ _ _ _ _._.o
l.n:I Cot4 h

When the a de gets executed, loop variable 'i' will be assigned values from oto n-t
I~ S In the nt 1terat1on It will pnnt tup(OJ, i.e., 'p' then tup{l J, 1.e., 'y' and so on up 1~
tup(S) .e n

CGIIIIII TUPLE OPERATIONS


Ang el e works With tuple as 1t did with lists, hke indexing, getting the length, etc. All
common sequence operation are available with tuples also.

Tuple.index(elem)

Tuple(range]

Tuplel +Tuple2

Tuple••

Tuple.count(elem)

,._ ,.1: Common Tuple Operations


~ tbe starting point
tbe stopping point, wblcll
15
: If di• steP s~ze-also Iman
tf01 ,dl fir51 index. slice starll
01
; pe1au11 ..I•• or step Is 1.
,,-"er. it includes the first
11ae first value in a tuple ts at
dfllbtnation with square brackets D

11
tuple1

»> tuplal • Cit


>>> tuple1[5:J '
(60, 70, 80, ,0)
>>>

Tl ( I MY BOOK I I

1 (2: ]

[ : ]
_,

•r

-1 as the step value, but the


. .ii111Mllat' lndudes
e-=t aD the elements from the tuple, Starting
flam, the above shce range will reverse the

elements from a tuple by changing the


II AdDn•u11111u111,aurn1t1on
111P
f,! v,;s you to 1nin/conratenat
al 1" e two tu pI
'rv1 ~ll(1
er11t11r·.
, oP 1 , ,, , l , 4 ) an bt added to a tuple uS1n1
f (

,.: c.. 6, 7, 8 )
( J ,

. g two tuples to form a new tuple


~"' Yt,,n,n
c,1fll
, ,< + y
, z )
' · nt ( Z
p!l.
~..... J 4 , S, 6, I , 8)
2 I I

•' se •+' operator with tuple sll 1


,art u ce a so.
foll l ( 1, 2 , 3 , 4 }
'ttlP
,., ir1:3J+(S , 6 )
, .. , t1JP
" 3, 5, 6)
,.. , 2 ' c.1 ', 4 )
..i- ( 1, I
',:;, ~ l [-3 : -1] +t..., [ ol #
will give erro
,:;,'7 t i< ( r . n+- 1l , ': as you arr. +-

i.' 4'> ", l'1 l, ,


" f ',
1[ l

r: ri n 1 y ·on ·r.1 n

'+' operator performs concatenation with tup es only.


)>> t 1 [ _ 3 : -1 ~ + ( t 1 [ Ol , l
~
1
, ' a', 1 )
CTM: We can only add tuple to a tuple.
-~~------11----------- -----'
NOTE: A single value included in () is treated a a single value and not as a tuple So. tf you
write (10) and ('a'), they are treated as integer nd string respectively But rf they are given
as (10,) and ('a',), these elements are treated as t pies with single element

9.6.3 Tuple Multiplication/Repetition


The multiplication operator(*) is used for repeti ·on of the tuple.

F,J,ldil M 0 . . , 0 , . . . - -
pythOn 3.6.5 (vJ.6.5:!5kO,J
7:46) [MSC v.1900 32 bit IID lll OD vial! tor mr
Type •copyright•, •credit.I• r •uceuell
e i nformation.
>>> X • (1,2,3,4)
>>> z • x•2
>» print (Z)
(1, 2, 3, 4, 1, 2, 3, 4)
'
>>> ( ' V ' ' , ) • 4 ,,.,.,, 'I I' I
( , BYE' I ' I .BYt I I , ,.. '
pp I in thl: tupl , oth rwtse
~

r 111\Dr

4 6 I

unllk II t tuples do not support methods such as apl>end()


rt nd pop() since all these operations require modifications to~
ot p rmnted
V r. lUp with veral built-in methods wl11lh a1 e as follows:

len(): Thi rn the I ngth of a tuple, ,.c., count the total number of elementstn
a tupl

~r 28 2018, 16:
J n w1n32
•11 .1e11• tor mor

,1 . )

4 J tau

,I
le b is an empty•
ct ruP
s111 d max()
11
_.1110 ' uon shall return the._.,.
• ..,1110 :::o
function shall return lb- dq I
~iod,~~r:r- - - - ~ ~

e the tuple 't' holds values of different types. 11111()


sine s work only with elements of same data lJpl.
tunct1on

Pyt
461 1-= v.uoe u Ill
Type "ccpyr1t11t•, .......
inforaatiOD.
>» 1 • 11, 2, , ••• II
>> t IMIIIII
~
(I))

p
1'■11i. --o ... ..ea() • • • .., . . c11a...-n •• • atrtna • •• baata
..,,,., ....1. . th t dlff r.nt characte Of ta....
, ... tla~~

chara r of RAHUL: and 'RAM' are same so


rll,■r:arl'9r and will rt-turn RAM a output ' it ""•II c0 ..._
·••p~t~
um of the elements of the tuple

.7.0 CYl.7. rlbf~,J, .1Un 21 2 18, 04: ,:47


.1tl4 J2 bit clatel)J on w1n32
1t1tt•, •crN.lt•• or •1tcenM(>• Cor 110re in

l • Cl0,Z2,SS,11,l,77,3 >
lel)

m n ton 5
mt mput n numbers from the user, store these numbers 1n a tuple and
Print th
um number along with the sum and mean of all the elements from th e
,. '

- .
.- ....ii. .. ,.- ◄

- "
a..- is tuple
.

••
• ....r• • __,.r• •(ma,)
--
_,,
...,...,_,._
,. --
.,.,.
Jt


111e . . . .n1a1a1-...-.
(It, zt, ..... It, ..
fllitMXiaa ..... &,


fllil
10
-1•'- ..... b
Tbe,_OftMlliplee.....
210
f11i1 ..Ill Of Yll. . ll U. "1lfle lt
,s.o
) >

,-ttd() ed to sort the elements of a tuple ft return a lilt altar 10f11111.


fO () 1S us
reed
so ,,,pie,
fo' etO ( , ' 4, , , ' I
' c,rted (
71 2 , , 4, , , ' 7I
1 , __........
'ting that the return type 1s a list and not a tuple The sequence n the ur....-,
rth no
is \.,,o . t changed and the data type of 'a' remains tuple
ft ' ' is no
ruPle ;i

• illdexO tion finds the first index of a given Item and returns the Index.
u1de"() func
0 tax:
SY index (va~ue.: , sta r t , end)
tUP1e .
t and end are two optional parameters for the start and end of the tuple 1
ttere, star
inde>'•

FM EM !WI 0.., 0,.0. ..._ "-


Python 3.6.5 (V3.6.5:t59c09)2b4, Nil' 28 2011,
32 bit (Intel)) OD vin32
r ype •copyriqht•, •credit.,• or •UCHN(I• for
>>> vote • 1• s•, • ", • 1 •, • •, )
>>> vote. index ( • • I
l
>>> vote.index(" "l
0
>>> vote.index(• •, l)
.2
· »> vote.i ndex(• •, 2)
4
>>> vote.index( • • , 1, 41
2
>» vote.index(
H Wtll 11 nt , d
II U, It 'lJ
I h Ill llt i

N IW I t d nth 11n1 I Ill( nt 1tlon of llldcxr)


.i11d to
of turl Utit( l
f1,"'
p
4u II y of I mcnts 111 c1 tuple

tl:
ti.ind x<e>:
•,ti.count( II

1 ~- 1 ·- _
RESTART: c:/Users/pr eti/AppData/Local/
t"
Coto

e tuple.py
£nter nwubers ~ parated by comma :
10,20,30,30,20,10,10,40,50,C 0,10
10 C
20 2
'JO 2
40 2
SO l
I
1 he abovC' program c.ounts the frequency of each element in a tuple. This is achi
. . eveu h
two hu1lt-111 functions available for tuple, ,.e., count() and index(). First, the input f Ylls1ng
elements 1-; fetched from the user using list comprehension, where each element or tup1~
I is ace eptec
t lrough input() c1nd each element 1s separated using split() and comma as the sepa
d . rator ihes,
In 1v1dual elements separated are stored as list elements, which are further conv
tuple b,> uc;,mg tuplel). ertect toa

All the elements of tuple are compared iteratively with each and every element pres
. ent in the
tuple r c1ch oc.currence of an element is counted usmg count(e) and for next iteration the.
tnde.x_ 1
1s mcremented by l and hence the output 1s so obtained.

Pr ut1c I lmi11cmenldllon-7
Program to perform linear search on a tuple of numbers.

,.. ,_..,o,e-w-
6)

lag•
~ n(Tuple)):
Tuple(1J •• n:

fll

la Cote
Riff GTUPLES
~p~ two tupk by u mg ro
CO 1P:1re
d1 cofl ,era tor c;Ldrl! by comp nn 1l r
? 11'1 oJl OJ 11 I
1 C•
11 1
,r,~ to LhC next rlement and Oun
,, t11l 0 11
, , ~
1
• 0eS con s1dc1 e<l (even II th yar r
f''~ I ,t i; , c ,,ot
,a,11~Jlleot5 ti
,.~
I

f,IC fdil
si,ttl~o,-s...,.._,
3. 6. 5 (VJ• 6.5: f59c0932b4
pyth~~o 32 bl t (Intel l] on vinJ2 lilt 2• 2 18, l6 1•4'1 llllt
", l "COPYright", •emits• or •11
-r';/P'3 t1n31 11 • t I aor, 1 f m1
iOil• (O, 1, 2) > (0, 3, 4)
,.,.,.
ra:i.se

,.,.,. (0 , 1, 20000001 < (0, 3, 4)


rrue Wlllt
tupl• (1, 2, 3) _. ...,........_
>>> tup2• fl.0,2 .0,3.0)
,.,.,. tupl••tup2
:,,>>
-r rue
Lat c.11,
(1, 2, 31
,>> tup!
(:C , L I
,>> tup2
>>> tupl tup2
-;rue

LETING ATUPLE
g8DE
· ternent is used to delete a tuple
rhe del sta
. . , .. 11111~ ..... - . . . _
Python 3,6. 5 (vl.6.5:mdl912b4, IH 21 2018, 1' l 45
(MSC v .1900 32 bit llnttll) 01 V1lll2
rype •copyugtt•, "tmiit.J" r •u~ 1• t r aan
rMtlon.
>>> tup• 11, 2, 3)
>> r (tupl
(l, 2, 3)
>>> tup
>>> r t (tup)
1,00 J2
,ri,e·
;,, d • ( ) ,-nt_l'tf_~~-~~•
,,,,,, dictl• ( 1·•
,,,,,, t (dictl)
('ll': 'll,I DJ', 'I'
,,,,,,

1111 second example, 'R', S', 'W' •


- n are the values associated•
.' I
I

.
• I
.
• I
.
• I
m

t(
I l'fl nt.atlOD 14

di on
op
. ,.
dtnga
the val
onartes can
one dtcttona

arnel,u
dlc_name2
e,

:40, :
at
)

, : ,

You might also like