12.4 Tuple Functions and Methods
122. Creating and Accessing Tuples 32.5. Indrecly Modifying Tuples
123° Tuple Operations
is chapter is dedicated to basic tuple mani
creating and accessing tuples,
built-in functions.
ipulation in Python, We shall be talking about
various tuple operations and tuple manipulations through some
12.2 Creating and Accessing Tuples
A tuple is a standard data type of Python that can store a sequence of values belonging to any type.
The Tuples are depicted through parentheses ie, round brackets, e,, following are some tuples in
Python :
O ‘# tuple with no member, empty tuple
(2.2.3), # tuple of integers
(1, 2.5, 3.7, 9) # tuple of numbers (integers and floating point)
(a0, '¢) # tuple of characters
(a, 1,"b, 3.5, zero’) _# tuple of mixed value types
Cone’, "Two!, Three!) # tuple of strings |
OTE
Before we proceed and discuss how to create tuples, one thing that Tuples are immutable sequences
Tuples are immutable (i.¢., non-modifiable) _°f PYthoni.e., you cannot change
ge elements of a tuple in place. elements of a tuple in place.
39798
12.2.1 Creating Tuples
Creating a tuple is similar to list creation, but het
parentheses. That is, use round brackets to in«
the items by commas. For example +
(2,4, 6)
(abe, 'def)
(2, 2.0, 3, 4.0)
oO
Thus to create a tuple you can write in the form given below
acy
value, .
»
This construct is known as a tuple display construct.
3. Long tuples
1. The Empty Tuple
The empty tuple is ( ). It is the tuple equi-
valent of 0 or”. You can also create an empty
tuple ai
T=tuple()
Tt will generate an empty tuple and name
that tuple as T.
2. Single Element Tuple
Making a tuple with a single element is tricky
because if you just give a single element in
round brackets, Python considers it a value
only, e.g.,
(1) was treated as a integer
expression, hence 1 stores an
integer 1, not a tuple
To construct a tuple with one element just add
a comma after the single element as shown
below :
doo t=3,
aot Both these ways
@,) wil reat tuples
>>> t2=(4,)
>>> t2
(45)
Creating Tuples from Existing Sequences
You can also use the built-in tuple type object
the syntax given below :
T = tuple(
)
where can be any kind of sequence object including strings, lists and tuples.
re you need to put a number of ex
te the start and end of the tuple, and
4. Nested tuples
(tuple( ) ) to create tuples from sequences aS)
COMPUTER SCIENCE WITH PYTHON _
Consider some more examples :
Ifa tuple contains many elements, then
enter such long tuples, you can splitit
several lines, as given below :
sqrs = (0, 1, 4, 9, 16, 25, 36, 49, 64,
81, 100, 121, 144, 169, 196,
256, 289, 324, 361, 400, 441,
484, 529, 576, 625)
Notice the opening parenthesis and
parenthesis appear just in the beginning:
end of the tuple.
If a tuple contains an element which is
tuple itself then it is called nested tuple:
following is a nested tuple :
t1=(2, 2, (3, 4))
The tuple tl has three elements in it:1,2:
@, 4). The third element of tuple t1 isa’
itself, hence, t1 is a nested tuple.
Note
Tuples are formed by
comma-separated | tuple
expressions in parentheses:
-0)chapter 12 + TUPLES 39!
python creates the individual elements of the tuple from the individual elements of passed
sequence: If you pass in another tuple, the tuple function makes a copy:
Consider following examples ;
>>> t1 = tuple(‘hello')
rere) Tapes created fom another sequence «ting “hello”
poet ‘It generated individual elements from the individual
(tt, es T
>>> L=[W, "er,
>>> t2=tuple(L)
>>> t2
Cw 'e rt Y)
You can use this method of creating tuples of single characters or single digits via keyboard
input. Consider the code below :
t1 = tuple( input(‘Enter tuple elements:'))
Enter tuple elements : 234567
>>> t 4 See, it created the elements of tuple t1
(2,°3,°8,'5,°8, 7)
See, with tuple( ) around inputt ), even if you not put parenthesis, it will create a tuple using
individual characters as elements. But most commonly used method to input tuples is
eval(input( )) as shown below
Tuple (2 is created from another sequence - alist L
1k generated individual elements from the
individual elements ofthe passed list L
using each of the character inputs
tuple = eval (input ("Enter tuple to be added:"))
print (“Tuple you entered :", tuple)
when you execute it, it will work somewhat like
Enter tuple to be added: (2, 4, "a", "hjkjl”, [3,4])
Tuple you entered : (2, 4, "a", "hikjl", [3,4])
Ifyou are inputting a tuple with eval(), then make sure to enclose the tuple elements in parenthesis.
Please note sometimes (not always) eval( ) does not work in Python shell. At that time, you can
run it through a script too.
IP) 12.1 write « program to create three tuples
| from the inputs given below :
Togrr
m ()“abeder” (i)3, 4, 5, 6
(ii) (21, 12, 13]
4s per the code given below considering
yam the three inputs of example 1
P 12.2 What will be the types of t1, t2, t3 created
og
E t1=eval(input("Enter input for tuplei : "))
‘1 =tuple(eval (input(“Enter input for tuple } t2=eval(input("Enter input for tuple2 : *))
‘$2 tuple(eval input("Enter input for tuple2 3 = eval(input (“Enter input for tuple3 : *))
+3 = tuple(eval (input("Enter input for tuple3 : print (“Type of t1 :", type(t1) )
Print ("Tuple 1 :", t1) print("Type of t2 :", type(t2) )
Print("Tuple 2 :", 2) print("Type of t3 :", type(t3)
Print("Tuple 3 :", t3) ee
Enter input for tuplel : “abcdef"
Enter input for tuple2 : 3,4, 5, 6
Enter input for tuple} : [11, 12, 13]
Tuple 1: (‘a’, ‘b’, ‘c’, ‘a’, ‘e’, ‘f7)
Tule 2: G, 4, 5, 6)
Tuple 3: (i, 12, 13)
Enter input for tuplel : “abcdef”
Enter input for tuple2 : 3, 4, 5, 6
Enter input for tuple3 : [11, 12, 13]
Type of tl :
Type of t2 :
Type of t3 : ‘As clear in program 12.2, the eval) decides the
‘ype depending upon the given input value, thus, we
used tuple() along with evai() in program 1.
single input value.
t1= eval (input(“Enter input for tuple :
print ("Created tuple is:", 1)
N
Enter input for tuple : 67,
Created tuple is: (67,)
Notice that we must puta comma?
after a single element, in onder
to be considered asa tuple
12.3. Write a program to create a tuple with a :
COMPUTER SCIENCE WITH PYTHON ~
12.4. Given below is a code, which is trying «9
create a tuple from a single element and ing
rg sample run. Why is the created variable
not of tuple type ?
+1 = eval (input("Enter input for tuple : *))
print ("Type of t1:", type(tt) )
input
m
Enter input for tuple : 67
Type of tl:
The above code is giving the type of created
variable t1 of int type because, while entering a
single value, no comma was added after it. Python
will consider a single value of tuple type only ifit
is followed by comma. Thus, to get the tuple type,
Wwe must add a comma after the input value, iz. as:
Enter input for tuple : 67,
type of tl:
»):
12.2.2 Accessing Tuples
Tuples are immutable (non-editable) sequences having a progression of elements. Thus, other
than editing items, you can do all that you can do with lists. Thus like lists, you can access its
individual elements. Before we talk about that, let us learn about how elements are indexed in
tuples.
12.2.2A Similarity with Lists
Tuples are very much similar to lists except for the mutability. In other words, Tuples are
immutable counter-parts of lists. Thus, like lists, tuple-elements are also indexed, i.e, forward
indexing as 0, 1, 2, 3,... and backward indexing as ~1, -2, -3,... [See Fig 12.1(a)]
tuplet = (a, 'e', 7, 0°, u')
a
(@) 5-4-3 2-1 < Backward indox
o[ +1 that because some of thelr objects are larger than
Coie Co aoa
Te
snare aR
(o) 3 459 ‘somewhere else in memory.
Figure 12.1 (a) Tuple Elements’ two way indexing (4) How tuples are internally organized.
Thus, you can access the tuple elements just like you access a list’s or a string’s elements
Tupleli] will give you element at i" index ; Tuple[a:b] will give you elements between indexes
ato b-1 and so on.copter 12 + TUPLES
put in other words, tuples are similar to lists in following, ways ;
© Length. Function len(T) returns the number of items (count) in the tuple T.
© Indexing and Slicing
Ti] returns the item at index i (the first item has index 0),
T[i:/] returns a new tuple, containing the objects between i and j excluding index j,
‘Tii :j: n] returns a new tuple containing every nth item from index i to j, excluding index j.
Just like lists
Membership operators. Both ‘in’ and ‘not in’ operators work on Tuples just like they work for
other sequences. That is, in tells if an element is present in the tuple or not and not in does the
opposite.
® Concatenation and Replication operators + and *. The + operator adds one tuple to the end of
another. The * operator repeats a tuple. We shall be talking about these two operations in a
later section 12.3 ~ Tuple Operations.
Accessing Individual Elements
‘As mentioned, the individual elements 12.5. Write a program to print a tuple’s first three and
of a tuple are accessed through their last three elements in the following manner
indexes given in square brackets just | rogram 1st element, last element
like lists. Consider the following 2nd element, 2nd last element
example: 3rd element, 3rd last element
>>> vowels = (‘a’, 'e’, ‘I’, ‘0, 'u)
aay ‘t1 = eval (input ("Enter input for tuple : "))
rs print( t1[@], t1[-1] )
Be tere dt print( t4[1], ta[-2] )
i A print( t4[2], t1[-3] )
>>> vowels[- 1] 3
E Enter input for tuple : 11, 12, 13, 14, 15, 16, 17, 18, 19
119
>>> vowels[- 5] RB
‘a Bi
Recall that like strings, if you pass ina AJ OTE
negative index, Fython adds the length of the. wnjieisédls ie MBe cle meHT Jollee nla Heeete
tuple to the index to getits forward index. That inde, python asthe lenath of the tuple to she naox vo
is, for a Gelement tuple T, TI-5] will be get element's forward index
intemally computed as :
TI-5+6]=TI[1J, and so on.
To see
Tuples vs sts
12.2.28 Difference from Lists ae
Although tuples are similar to lists in many ways, yet there is an important Geel |
difference in mutability of the two. Tuples are not mutable, while lists are. mee |
You cannot change individual elements of a tuple in place, but lists allow ae
You to do so.
aa i~~
4 SCIENCE
402 COMPUTER SCIENCE WITH PYTHON
That is, following statement is fully valid for lists a
c (BUT not for tuples). That is, if we have a list L and a
ee Te nd ac
Se ipecienens but they are different in the sense that tuples ag
is VALID for Lists. BUT immutable while lists are not.
T[i] = element nn
is INVALID as you cannot perform item-assignment in immutable types.
EXAMPLE BM) Consider a tuple created as #1 = (11,21, 31, 42, 51). By mistake the 2nd las element ofthe tuple
is entered as 42 in place of 41. And now, if we try to modify it using statement f1[-2] = 41, Python is giving erro
there a way to accomplish this ?
SOLUTION
Python is giving error for t1[-2] = 41, because tuples are immutable types and we cannot change
any of its element in place (item assignment not supported in tuples).
But we ever need to change any element of a tuple, like this case, we can cast the tuple toa list type,
modify the element and recast it to a tuple type. This trick is covered in section 12.5 and program 1214.
12.2.2C Immutable Types with Mutable Elements
So now it is clear to you that immutable type like tuples cannot have item assignment, ie, you
cannot change its elements. But what if a tuple contains mutable elements e.g., a list at its element?
In that case, would you be able to modify the list elements of the tuple or not ? Well, read on.
If a tuple contains mutable elements such lists or 7552-016
dictionaries, then tuple’s elements once assigned numbers
will not change, but its individual mutable 1 i
elements can change their own elements’ value HHS
Tounderstand, go through the following example.
Say you have a tuple which stores two elements of pose
list types : 3
>>> numbers = ([1, 2, 3], [4, 5, 6]) o
! Internally, the above tuple will store its list
elements as shown in adjacent figure.
Now if you try to modify the elements of tuple To soe
numbers by giving a statement like : ieee
>>> numbers[1] = [1, 2, @] Ham
Traceback (most recent call last) : F |
File "", line 1, in a
numbers[1] = [1, 2, @] a
‘Typetrror: ‘tuple’ object does not support item assignment cr ca)
This is because, the above is trying to change the first element of tuple numbers but as tuples
immutable, no matter what, the tuple numbers will always keep referring to its first list
stored at address 8016, That isthe address ofits first list element will always remain 8016.
But if you give a statement like
>>> numbers[@][2] =@
aPee
(
Chat
jpter 12 + TUPLES
It will give no error. This is because, the tuple ath
numbers’ elements’ memory addresses are not numbers
changed; the tuple numbers is still referring to [_¢ ¢
same Python list objects stored at addresses 8016
and 9032 respectively. However, the list stored at r]
address 8016 is now having different elements, 90:
which is allowed as lists are mutable and their
elements can change. So after the above 4
statement, internally the tuple numbers will be g
like as shown adjacent figure (as you can see, the
addresses of its list elements are unchanged) :
eh
So now if you print the numbers tuples, it will give you result as :
>>> print(numbers) . S071
([1, 2, @1, [4, 5, 61) Nore
Solved problem 11 is based on this" immutable tuple can store mutable elements and its mutable
elements’ individual elements can be changed. The immutable object's
soncept.
sFery, concer, elements are always the same Python object, but aren’t always the same
abstract value.
12.2.2 Traversing a Tuple
Recall that traversal of a sequence means accessing and processing each element of it. Thus
traversing a tuple also means the same and same is the tool for it, iz, the Python loops. The for
loop makes it easy to traverse or loop over the items in a tuple, as per following syntax :
for - in
process each item here
For example, following loop shows each item of a tuple T in separate lines =
T= (PY, "tH, ‘0, 'n) Pp
forainT:
print (T[a])
The above loop will produce result as :
How it works
The loop variable a in above loop will be assigned the Tuple elements, one at a time. So,
loop-variable a will be assigned ‘P’ in first iteration and hence ‘P’ will be printed; in second
iteration, a will get element ‘y’ and ‘Y’ will be printed ; and so on.
If you only need to use the indexes of elements to access them, you can use functions range() and.
en() as per following syntax :
or index in range(1en(T)):
process Tuple[index] here
Consider program 127 that traverses through a tuple using above format and prints each item of a
tuple L in separate lines along with its index.404 COMPUTER SCIENCE WITH PYTHON — x
12.6 Program to print elements of a tuple (‘Hello', “Isn’t”, ‘Python’, ‘fun’, “2”) in separate lines al
‘with element's both indexes (positive and negative).
ogra
m T= (Hello’, ‘Isn't’, Python’, "fun', '?)
length = len(T)
for a in range(1ength) :
print (‘At indexes’, a, ‘and ', (a - length), ‘element :', T{a])
‘At indexes 0 and -5 element : Hello
‘At indexes 1 and -4 element : Isn't
‘At indexes 2 and -3 element : Python
‘At indexes 3 and -2 element : fun
‘At indexes 4 and -1 element : 7
Now that you know about tuple traversal, let us talk about tuple operations.
12.3 Tuple Operations
The most common operations that you perform with tuple include joining tuples and slicing
tuples. In this section, we are going to talk about the same.
12.3.1 Joining Tuples
Joining two tuples is very easy just like you perform addition, literally ;). The + operator, the
concatenation operator, when used with two tuples, joins two tuples.
Consider the example given below :
>>> tpl = (1, 3, 5)
>>> tpl2 = (6, 7, 8)
>>> tpl1+ tpl2
The + operator concatenates two tuples
‘and ereates a new tuple
uals
(4, 3, 5, 6, 7, 8)
‘As you can see that the resultant tuple has firstly elements of first tuple Ist and followed by
‘elements of second tuple [s#2. You can also join two or more tuples to form a new tuple, €g.,
>>> tpl = (10, 12, 14)
>>> tpl2 = (20, 22, 24)
>>> tpl3 = (30, 32, 34) The + operator is used 10 concatenate
>>> tpl = tpli + tpl2+ tp1347 thre individual tuples to get a new
combined tu
>>> tpl si Baty
(10, 12, 14, 20, 22, 24, 30, 32, 34)
‘The + operator when used with tuples requires that both the operands must be of tuple types.
You cannot add a number or any other value to a tuple. For example, following expressions will
result into error :
‘tuple + number
tuple + complex-number ERROR
tuple + string .
tuple +listChopier 12 # TUPLES
Consider the following examples :
>>> tpl = (18, 12, 14)
‘Seo errors generated when anything
frearcs Pan ‘other than a tuple is added to a tuple
‘TypeError: cah only concatenate tuple (not “int") to tuple
>>> tpl + "abc"
TypeError: can only concatenate tuple (not "str”) to tuple
‘The tuples being immutable, expand to a=a +b for a +=, where both a and b, are tuples.
IMPORTANT
Sometimes you need to concatenate a tuple (say tpl) with another J OTE
tuple containing only one element. In that case, if you write
A single value in ( ) is treated as
statement like :
single value not as tuple. That is,
>>> tpl + (3) expressions (3) and. (‘a’) are
. integer and string respectively
Python will return an error like but (3,) and ‘a, ) are examples of
tuples with single element.
Typetrror: can only concatenate tuple (not “int") to tuple
The reason for above error is that a number enclosed in ( ) is considered number only. To make it a
tuple with just one element, just add a comma after the only element, i, make it (3,). Now Python
won't return any error and successfully concatenate the two tuples.
>>> tpl =(18, 12, 14, 20, 22, 24, 3@, 32, 34)
>>> tpl + (3, ) <————
(1@, 12, 14, 20, 22, 24, 3, 32, 34, 3)
Single element tuple
Repeating or Replicating Tuples
Like strings and lists, you can use * operator to replicate a tuple specified number of times,
if tplt is (1, 3, 5), then
p>> tpi #394
(1, 3, 5, 1, 3, 5, 1, 3, 5) Noe
OTE
12.3.2 Slicing the Tuples i Se ee
Tuple slices, like list-slices or string slices are the sub parts of the tuples, the + operator requires
tuple extracted out. You can use indexes of tuple elements to both the operands as tuple-types;
create tuple slices as per following format and the * operator requires a tuple
and an integer as operands.
seq=T[start:stop]
eg.,
— The * operator repeats a tuple specifies
‘number of times and creates a new tuple
The above statement will create a tuple slice namely seq having elements of tuple T on indexes
start, start+1, start2, ...,stop-1. Recall that index on last limit is not included in the tuple slice.
‘The tuple slice is a tuple in itself that is you can perform all operations on it just like you perform
on tuples. Consider the following example :
>>> tp’ (10, 12, 14, 20, 22, 24, 30, 32, 34)
>>>seq= tpl [ 3:-3]
>>> seq
(20, 22, 2a)
Pe iCOMPUTER SCIENCE WITH PYTHON « 9
For normal indexing, if the resulting index is outside the tuple, Bi as if
IndexError exception, Slices are treated 4 — ristart:stop] creates» tuple seg
iar Gea and the result "ail simply contain all aed cout of tuple T with elements
between the boundaries. For the start and stop given Ree falling between indexes stort ang,
tuple limits in a tuple slice, Python simply returns the element
that fall between specified boundaries, if any.
For example, consider the following :
>>> tpl =(10, 12, 14, 20, 22, 24, 30, 32, 34)
; the sce ofthe tpl, but
>>> tp] [3:38] ¢——————— Ginn upper limit ay beyond tea of ET
(20, 22, 24, 30, 32, 34) ie ere ae
>>> tpl [-15 :7] Seer ae
(18, 12, 14, 20, 22, 24, 38) Giving lower limit much lower, but python returns elements
{from tuple falling in range ~ 15 onwards <7
msecuti’
Tuples also support slice steps too. That is, if you want to extract, not om ae but
other element of the tuple, there is a way out ~ the slice steps. The slice steps are used as per
following format :
seq=T[start:stop: step]
Consider some examples to understand this,
>>> tpl
(10, 12, 14, 20, 22, 24, 3@, 32, 34)
>>> tpl[@:10:2] ~~ Include every 2nd element, ie, skip | element
) in benveon. Check ruling tuple slice
(10, 14, 22, 30, 34)*~ -
>>> tpl[2:10:3]
(a4, 24, 34)
) patie) ae stop given. Only step is given as 5,
(18, 20, 30) ‘That is from the entire tuple, pick every 3d element forthe tuple
Include every 5rd element, i. skip 2 element in between
Consider some more examples :
seq=T[::2] get every other item, starting with the first
Seq=T[5::2] # get every other item, starting with the
# sixth element, i.e., index 5
You can use the + and * operators with tuple slices too. For ll
example, ifa tuple namely Tp has values as (2, 4, 5, 7, 8, 9, 11,12, Note
34), then : Tistart : stop: step] creates 2
af See, the * operation has multiples the ‘UME slice out of tuple T with
>>> Tp [2:5] #3 ate sie and nt the a elements falling between
(5,7, 8, 5,7, 8, 5, 7, 8) Indexes start and stop, nat
>>> Tp[2:5] + (3, 4) Including stop, skipping step
(SHAE) elt —— ow tr Serr hx oad elements in between,
iver tuple 0 the ple slice
SEcpr 122 TURES
a 12.7 Waite a program to input a tuple and create two new tuples from lt, one containing Is every rd
element in reverse order, starting from the last element another containing every alternate elements
5 siron _Uvng between 3rd 10 th elements
i up = eval (input ("Enter input for tuple : "))
cae tuell Saal Enter input for tuple t 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11
; 7 Two created tuples art
tuple 1: (i, 8, 5, 2)
Tuple 2: G3, 5, 7)
12.8 Given three tuples as shown below :
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
ryan (A, 2, 3, 4, 5, 6, 7, 8, 9, 10)
| (1, 2, 3,4, 5, 6,7, 8, 9)
Which of the above three tuples will produce the two tuples having identical elements but in reverse order as per the
: code given below ?
tup= eval (input ("Enter input for tuple : "))
Enter input for tuple : 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12
‘Two created tuples are :
Tuple 1: (3, 5, 7)
Tuple 2: (9, 7, 5)
print ("Two created tuples are:
print(“Tuple 2 :", t1)
print(“Tuple 2 :", t2) Enter input for tuple
| Two created tuples are
| Thetuple (1, 2, 3, 4, 5, 6, 7, 8, 9) will Tuple 1: (3, 5, 7)
give the two tuples having same qhunle 2 a6Snibad)
elements in reverse order. Enter input for tuple : 1, 2, 3, 4, 5, 6, 7, 8, 9
Two created tuples are :
tuple 1: @, 5, 7)
Tuple 2: (7, 5, 3)
Comparing Tuples
You can compare two tuples without having to >>> arb
write code with loops for it. For comparing two, False
tuples, you can using comparison operators, i.., Spas (oteratey
<>, =; !rete. For comparison purposes, Python seas
internally compares individual elements of two fan
| tuples, applying all the comparison rules that you —
have read earlier. Consider following code : od
>>> a= (2, 3) True Gh
otic for comparison purposes,
>>> b= (2,3) ene bo>@= (2,3, 4) Phon ignored the ype of
>>> aseb RTE, 422,056 lve nd compre as
True (coal int and float with aiak
nan ‘i
| >ooce(2', 13!) femal You can refer to table 11.1 that discusses non-
; >> asec
equality comparisons of two sequences. Elements
in tuples are also compared on similar lines.
False
—Juces two tuples that co
12.9 For a specific tuple, the code given in the previous de Pate ‘example’s code) ty
| elements in reversed order: Write a program (by modifying P' 1
‘wo tuples contain the same elements in reversed order. a "
‘tup = eval (input ("Enter input for tuple ‘"))
tls tup[ 2:8:2]
i 2=tup[ -3:-9:-2] oo
, t3=t2[::-1]
ift3==t1:
sed order.")
print("The two tuples contain the same elements in rever:
else:
print("The two tuples contain different elements
Eitersinputifon tuple : 1, 2, 3, 4, 5, 6,(75 8, 97 10, ‘11
The two tuples contain different elements.
Enter input for tuple.:.1,)2, 3, 4,5, 6) 7.8, 9
The two tuples contain the same elements in reversed order.
Unpacking Tuples oan eae a
arial d
Creating a tuple from a set of values is called ‘uple t Pe is: you! aa
Packing and its reverse, i, creating individual @55i8nn eet values of these
values from a tuple's elements is called unpacking _i"dividually print the
somewhat like :
Unpacking is done as per syntax : "The adjacent
, , , . yield oe
print (w)
where the number of variables in the left side of print (x)
assignment must match the number of elements print (y)
in the tuple. For example, if we have a tuple as: melt
t=(1, 2, ‘A, 'B)
The length of above tuple tis 4 as there are four
elements in it. Now to unpack it, we can write:
WX Ys
“Tuple unpacking requires that the ki
‘ariables on the left has the same number
Ne eet eine elements as the length of the tuple”
variables on LHS in parenthesis Guido van Rossom.
1 will give you same result
12.10 Write a program to input a 4-element tupl
le and unpack it to four variables: Then recreate the fi
with elements swapped as Ist element
with 3rd and the 2nd element with the 4th element.
rogram tup = eval (input (“Enter a4 element tuple : "))
a,b,c,d= tup
print("Tuple unpacked in",a, b, c, d) 5
tup=c,d,a,b Nore
print (“Tuple after swapping the elements:*
» tup) Forming a tuple from indivic
i is called packing at
Enter a 4 elenent tuple : 10, 20, 30, 40 credtng tienda ee
Tuple unpacked in 10 20 30 40 tuple’s elements is calle
Tuple after swapping the elenents: (30, 40, 10, 20) unpacking,Fete
|
|. chop 12°» TUPLES
Deleting Tuples
‘The del statement of Python is used to delete elements and objects but ae you know that tuples
are immutable, which also means that individual elements of a tuple carinot be deleted, ic, if
you give a code like :
>>> del f1[2]
Then Python will give you a message like :
Traceback (most recent call last):
File "", line 1, in
del t1[2]
TypeErrot
“tuple' object doesn’t support item deletion
But you can delete a complete tuple with del statement as :
del
For example,
>>> tL= (5, 7, 3, 9, 12)
>>> tl
(5, 7, 3, 9, 12)
>>> del t1 KE
>>> print(t1)
Traceback (most recent call last):
File "," line 1, in
print(t1) See, after using del statement on a tuple, if you try to
INameError: name ‘ti? isnot defined «277i wccms/ mill #| Py gil ee a
been deleted and this objets exists no more
12.4 Tuple Functions and Methods
Python also offers many built-in functions and methods for tuple manipulation. You have
already worked with one such method len( ) in earlier chapters. In this section, you will lear
about many other built-in powerful tuple methods of Python used for tuple manipulation. Let
| us now have a look at some useful built-in tuple manipulation methods.
1. The len( ) function
This method returns length of the tuple, ie.,
the count of elements in the tuple.
£2. The mox( ) function
This method returns the element from the
tuple having the maximum value.
ya Syntax :
| "NEES max()
~ Takes tuple name as argument and = Takes tuple name as argument and
returns an integer. returns an object
Example : E (the element with maximum value).
>>> employee = (‘John’, 10000, 24, 'Sales') :
. >>> len (employee)
Seema Th ent) etna te Court op
elements in the tupleCOMPUTER SCIENCE WITH PYTHON —
Example :
>>> tpl = (10, 12, 14, 20, 22, 24, 30, 32, 34)
2>>.ax(tP1) 4 —————— asin sai fom cup Uh I reared
34
>>> tpl2 = (“karan",
>>> max(tp12)
“Zubin <————_steximum value rom tuple it2 is returned
tubin", "Zara", "Ana'
Please note that max() applied on sequences like tuples/lists etc. will return a maximum value
ONLY IF the sequence contains values of the same type. If your tuple contains values of
different datatypes then, it will give you an error stating that mixed type comparison is not
possible
@ >>> ab=(1, 2.5, "1", [3,4], (3,4) )
>>> max(ab)
Typerrot
(6) >>> ab= ([3,4], (3,4) )
>>> max(ab)
>! not supported between instances of ‘str’ and ‘float
TypeError: *>' not supported between instances of ‘tuple’ and ‘list’
3. The min( ) function
This method retums the element from the!
tuple having the minimum value. Syntax
min()
— Takes tuple name as argument and returns
4an object (the element with minimum value)
Example : :
>>> tpl = (10, 12, 14, 20, 22, 24, 30, 32, 34) |
>>> min(tpl) :
10 <—— Minimum value from tuple tpl is returned
>>> tpl2 = ("Karan", "Zubin", "Zara", "Ana")
>>> min(tp12)
‘Ana! <——— inimum value frov: tuple tp2 is retuned:
Like max( ), for min() to work, the elements of !
tuple should be of the same type.
4. The sum( ) function
‘The sum( ) function takes the tuple sequence
and returns the sum of the elements of the tuple.
For sum() to work, the tuple must have :
numeric elements. é
Function sum( )
syntax
works as per the following
sum ()
where the is a tuple of elements
whose sum is to be calculated.
For example, consider the tuple
val = (27, 34, 25, 40) :
>>> sum( val )
126 {
The index( ) method |
j
The index( ) works with tuples in the same
way it works with lists, That is, it returns the
index of an existing element of a tuple. It is
used as :
. index (- )
Example: >>> t1=[3, 4, 5, 6.0]
>>> t1index(5)
2
But if the given item does not exist in tuple, it
raises ValueError exception.penetra
minimum element in a tuple,
oro
tup=eval(input("Enter a tuple : "))
nn =min(tup)
print ("Minimum element", mn, \
“{s at index", tup.index(mn))
enter a tuple : 23, 22, 11, 9, 10, 15
winimum element 9 is at index 3
4, The couni( ) method
‘The count() method returns the count of a
member element/object in a given sequence
(isttuple). You can use the count( ) function |
as per following syntax : |
. count ()
12.11 Write a program to print the index of the
Example :
pp t= (2, 4, 2, 5,7, 4, 8, 9, 9, 11, 7, 2)
>>> t1.count (2)
3 <————_ There are 5 occurrence of element 2
Pe StIECOUMTE( 7) genomes ee ciromec onan
2
>>> tL. count (11)
A
Foranelement not in tuple, it returns 0 (zero).
12.12 Write a program to input a tuple and
check if it contains the all elements as}
rosa
ma same.
tup = eval (input (“Enter a tuple : "))
In= len(tup)
num = tup. count (tup[@])
if num==1n:
prine("Tuple contains all the same elenents.") |
else:
print("Tuple contains different elements.)
Enter a tuple : 23,23,23,23
Tuple contains all the same elements.
7. The sorted( ) function |
This function takes the name of a tuple’ as a1
argument and returns a new sorted list with
It works as per the following syntax :
sorted(, (reverse = False] )9
where
= is the tuple tobe sorted
= argument reverse is optional and takes a
boolean value. If reverse argument is missing,
(or set to False), then the tuple elements are
sorted in ascending order. If reverse argument
is set to True, then the tuple elements are
sorted in the reverse order (descending).
For example, for a tuple val = (27, 34, 25, 40),
sorted( ) will work as
>>> sval = sorted(val)
>>> sval +——__ see, the sorted( ) created a new list
which is sored in ascending order of
[25, 27, 34, 40] the elements
>>> rsval = sorted( val, reverse = True)
>>> rsval +——__ See, the sorted ) with argument
reverse = True, created a new list
[40, 34, 27, 25] which is sorted in descending
order of the elements
Please note that the sorfed( ) function will
always output the result of list type.
The tuple{ ) method
This method is actually the constructor method
that can be used to create tuples from different
types of values. It works as per the following
syntax :
tuple()
~ Takes an optional argument of sequence type ;
Returns a tuple.
— With no argument, it returns empty tuple
Example :
© Creating empty tuple
>>> tuple()
10)
© Creating tuple from a string
>>> t = tuple(“abc")
>>o>t
(a,b, 'c)
ee elements in it. | |
The
sorted() function can take argument of any iterable sequence type like lists, tuples etc., butiitretums always sorted lst.a”
12 COMPUTER SCIENCE WITH PYTHO}
© Creating a tuple from a list ‘The tuple( ) and list( ) are constructors
>>> t= tuple([1,2,3]) you create tuples and lists respectively
>t {passed sequence, This feature can be exploit
(2, 2,3) | asa trick to modify tuple, which otherwise.
ai not possible. Following section talks about
same.
© Creating a tuple from keys of a dictionary
>>> t= tuple ( {1:"1", 2:"2"})
12.13 Write a program to input a tuple
>>> t1 i sort its elements. At the end of
Hee program, all the elements of the tiple
As you can notice that, Python has considered: "8°" ‘should be sorted in ascending order,
only the keys of the passed dictionary to create
tuple. But one thing that you must ensure is
td = eval(input ("Enter a tuple : "))
that the tuple( ) can receive argument of Ast = sorted(t1) a
iterable sequence types only, i.e, either a string. t1= tuple(1st) ‘
ora list or even a dictionary. Any other type of ! print(“Tuple after sorting:", t1)
value will lead to an error. See below : i
>>> t = tuple(1) il enter a tuple : 23, 22, 11, 9, 10, 159m
tuple after sorting: (9, 10, 11, 15, 22,
TypeError: ‘int’ object is not iterable
Summary of Tuples Manipulation Functions ond Methods
[etior| Function / Method | i Description
1, |1en() This function returns length of the tuple,
___| elements in the tuple. a
2. |max() This function returns the element from the tuple having
“" maximum value. ;
3. |min() This function returns the element from the tuple having’
___ | minimum val a
4, | sum () The sum( ) function takes the tuple sequence and returns tit |
sum of the elements of the tuple.
5. | ctuplename> . index () ‘The index( ) method works with tuples in the same way.
works with lists. That is, it returns the index of an existing |
element of a tuple.
6. | .count() | The count( ) method returns the count of a memt
element/object in a given sequence (list/tuple).
7. | sorted(,
t se]
‘tuple()
12.5 Indirectly Modifying Tuples
Tuples are immutable counterparts of lists. If you need to modify the contents often
sequence of mixed types, then you should go for lists only. However, if you want to
that a sequence of mixed types is not accidently changed or modified, you go for ti| gt
{
—
chopler 12 = TUPLES
But sometimes you need to retain the sequence as tu
one point of time, then you can use one of the two methods given here,
(o) Using Tuple Unpacking
Tuples are immutable, To change a tuple, we would need to first unpack it, change the values,
and then again repack it :
tpl = (11, 33, 66, 99)
1, First unpack the tuple :
a,b,c,d=tpl
413
iple and still need to modify the contents at
2. Redefine or change desired variable say, ¢
cs77
3. Now repack the tuple with changed value
tpl=(a, b, c, d)
%
3
5 12.1
4, Why are tuples called immutable types 2
2, What are mutable counterparts of tuples ?
3, What are different ways of creating
tuples ?
4. What values can we have in a tuple ?
Do they all have to be the same type* ?
5. How are individual elements of tuples
accessed ?
6, How do you create the following tuples ?
() (4,5, 6) (b) (-2, 1, 3)
(2 (-9, -8, -7, -6, -5)
@ (9, -10, -11, -12)
(©) (@, 1, 2)
7. Ifa (5, 4, 3, 2, 1, 0) evaluate the
following expressions :
() af@] ala] (© alale}]
(@ ala[-1}]
(2) afafafa[2]+1]]]
§ Can you change an element of a
Sequence ? What if the sequence is
a dictionary ? What if the sequence is a
tuple ?
. What does a +b amount to if a and b
ae tuples ?
10. What does a * b amount to if a and b
ae tuples ?
What does a+b amount to if ais a
tuple and b= 5 ?
Ts a string the same as a tuple of
characters ?
Can you have an integer, a string, a
tuple of integers and a tuple of strings
ina tuple ?
nh,
2,
1B.
(6) Using the constructor functions of
lists and tuples i.e., list( ) and tuple( )
There is another way of doing the same as explained below :
>>> tpl = ("Anand”, 35000, 35, “Admin")
>>> tpl
(Anand, 3500, 35, ‘Admin')
1. Convert the tuple to list using list() :
>>> Ist = list (tpl)
>>> Ist
[ Anand’, 35000, 35, ‘Admin’)
2. Make changes in the desired element in the list
>>> Lst[1] = 45000
>>> Ist
['Anand’, 45000, 35, ‘Admin’]
3. Create a tuple from the modified list with tuple( )
>>> tpl = tuple(1st)
>>> tpl
['Anand’, 45000, 35, *Admin’]
Isn't the trick simple? ©
12.14 A wple t stores (11, 21, 31, 42, 51), where its second
last element is mistyped. Write a program to correct its
second last element as 41
rogram
t1= (11, 21, 31, 42, 51)
tli = list(t1)
tli[-2] =41
ti = tuple(tl1)
print("Modified tuple : ", t1)
Modified tuple : (11, 21, 31, 41, 51)