CH - 12 TUPLES
CH - 12 TUPLES
TUPLES
TOPICS
INTRODUCTION
Tuple is an another sequence data type.
Advantages:
It supports Immutability.
It supports heterogeneous.
It supports multi-dimensional.
(or)
Example:
To construct a Tuple with one element, Just add a comma after single element.
Syntax:
Variable_Name=tuple(value,)
Example:
If comma is not there in a single element type of tuple then Python will consider it as
expression not a tuple.
(iii) Long element Tuple:
We can create a tuple with multiple elements in single line or in multiple line. This type
of tuple is called Long element tuple.
Syntax:
Variable_Name=(Value1,Value2,Value3 …..Value n)
(or)
Variable_Name=(Value1,Value2,Value3,
Value4,Value5,Value6)
Example:
(iv) Nested Tuple:
If a tuple contains another tuple inside of it, then it is called Nested Tuple.
Example:
MEMORY REPRESNTATION OF
LIST & NESTED LIST
Each element or an item of an tuple is stored in contagious memory location(one after
other). Each item has its own positive & negative indices.
For Example:
T1=(10,20,33,44) 10 20 33 44
0 1 2 3
-5 -4 -3 -2 -1
T2=(1,2,(30,45),50,60) 1 2 50 60
0 1 2 3 4
It allows user to access elements from tuple by using particular index value.
Syntax:
Tuple_Variable_Name[index_value]
Example:
(ii) Traversing a Tuple:
“in” operator used with for loop iterates each element of a tuple in sequence.
O/P:
Example - 1:
(or)
Example -2:
O/P:
EXAMPLE PROGRAMS USING TUPLE
1. Write a Python program to accept string from user and display only consonants.
Sample Output:
2. Write a Python program to search a particular element from the tuple using linear
search method. If element is found display its index/Location. Otherwise print
appropriate message.
SLICING THE TUPLE
Slicing:
List slice refers to a part of the List, where List are sliced using a range of indices.
(or)
Slicing is an operation that can be performed on the sequence to get part of the
sequence.
Syntax: Variable_Name[start:end:step]
Where,
Start -> It is starting index from where we want to start the extraction.
Step -> It is the increment/decrement value which specifies next index to be extracted.
Further we way use the above general syntax in different ways to slice the Tuple:
vi. Tuple[:] Extract the entire List 0th index to till last index.
vii. Tuple[ : : step] This will print alternative element according to step size.
Note:
In the above syntax start value is included and end value is excluded.
TUPLE SLICING EXAMPLES
PRACTICE QUESTION - 1
1. Create a Tuple Sports with values Cricket, Hockey, Tennis, Football, Kho kho. Print the
value of first element?
2. Create a Tuple Fruits with values Mango, Orange, Apple, Grapes, Pineapple and write
suitable statements to do the following operations:
The + operator when used with the tuples it requires both the operands must be of
tuple types.
We cannot add a number or any other value to a tuple i.e. tuple + (number (or)
complex (or) list (or) string (or) set (or) dictionary ) . Results error (type error).
Example:
Concatenation operator can also be used for extending an existing tuple.
Example - 1:
Example – 2:
The repetition operator requires the first operand to be a tuple and the second
operand to be an integer only.
Using ‘in’ & ‘not in’ operator we can check whether the element is exist in the tuple or
not.
The in operator returns true if the element present in tuple otherwise false.
The not in operator returns true if the element is not in the tuple otherwise false.
Example:
(iv) COMPARISON OPERATORS
We can compare two tuple or more by using comparison operators < ,<=,>,>=,==,!=
The comparison operators starts by comparing the first element from each sequence ,
If they are equal it goes on to next element & so on until if finds the element that
differ.
Eg:
EXAMPLE PROGRAM FOR CREATING TUPLE BY USING USER’S
INPUT DURING RUN TIME
1. Write a Python code to get ‘n‘ number of integers from user and store them into tuple.
2. Write a Python program to store 'n' number of subject in a tuple using for loop.
EXAMPLE PROGRAM FOR CREATING TUPLE BY USING USER’S
INPUT DURING RUN TIME
3. Write a Python program code to create nested tuple using for loop to store
Roll number, name and age of students.
Sample Output:
Modifying and deleting tuples
In Python tuples are immutable i.e. once we define tuple, modification & deletions
of an individual element are not allowed.
Example:
>>> T=(10,20,30,40)
>>> T[0]=45
Error:
The above will raise type error which states tuple object does not support an item
assignment.
INDIRECTLY MODIFYING TUPLES
Since Tuples are immutable, we cannot modify the tuple elements directly.
But we can indirectly modify the tuples by using two ways. They are:
Example:
>>> T=(10,20,30,450)
a=10 b=20 c=30 d=450
>>> print(T)
NOTE: The number of variables in the left side of
(10,20,30,40)
assignment must math the number of elements in the
tuple.
(ii) Using Constructor function
(i) Convert the tuple variable into list. Using list constructor -> list( )
>>> tp2=(20,'Anand',45,'Admin')
>>> S=list(tp2)
>>> S[2]=25
>>> S[3]='manager'
>>> tp2=tuple(s)
>>> tp2
(20,'Anand',25,'manager')
DELETING TUPLE ELEMENTS
The del statement of python is used to delete elements and objects of the tuple.
But, tuples are immutable so we cannot delete individual elements of tuple using
del.
Example:
>>> tp1=(10,20,30,40,50)
Example:
>>> tp1
Syntax:
len(Tuple_variable_name)
Example:
(ii) min ( )
➢ This function returns the total number of elements in Tuple, passed as argument to len
method.
Syntax:
min(Tuple_variable_name)
Example:
(iii) max ( )
➢ This function returns the maximum/biggest element from the Tuple.
Syntax:
max(Tuple_variable_name)
Example:
(iv) sum()
➢ This function returns the sum of elements of a Tuple
Syntax:
sum(Tuple_variable_name)
Example:
(v) tuple()
➢ This function returns a tuple created from passed argument as a sequence
type(list,string,tuple)
Syntax:
Tuple(Sequence_variable_name)
Example:
(vi) sorted()
• This function takes the name of a tuple as an argument and returns a new sorted list
with sorted elements in it.
• Sorted() with argument reverse=True created a new list which is sorted in descending
order of the elements
Syntax:
sorted(Tuple_Variable_Name, reverse=True/False)
Example:
(vii) t.index()
This method returns the index of first matched item from the Tuple.
Syntax:
Tuple_Variable_Name.index(Value)
Example:
(viii) t.count()
This method returns the count of an element in a given tuple.
Syntax:
Tuple_Variable_Name.count(element)
Example:
PRACTICE QUESTIONS
1. Why are tuples called immutable types?
4. What values can we have in tuple? Do they all have to be the same type?
10. Can you have an integer, a string, a tuple of integers and a tuple of strings in a tuple?
PRACTICE QUESTIONS
1. Find the output generated by following code fragments:
a. Plane = ("Passengers", "Luggage")
Plane[1] = "Snakes"
Sol:
b. (a,b,c)=(1,2,3)
Sol:
c. (a,b,c,d)=(1,2,3,4)
Sol:
PRACTICE QUESTIONS
d. >>> a,b,c,d =(1,2,3)
Sol:
e. (a,b,c,d,e)=(p,q,r,s,t)=t1
Sol:
Sol:
PRACTICE QUESTIONS
g. >>> t2 = ('a')
Sol:
h. >>>t3=('a',)
>>> type(t3)
Sol:
PRACTICE QUESTIONS
i. >>> T4=17
>>> type(T4)
Sol:
j. >>> T5=(17,)
>>> type(T5)
Sol:
<class 'tuple'>
# because T5 is a single element tuple made by using " , “ after the element.
PRACTICE QUESTIONS
k. tuple=('a', 'b', 'c', 'd', 'e')
tuple=('A',)+tuple[1:]
print(tuple)
Sol:
l. t2=(4,5,6)
t3=(6,7)
t4=t3+t2
t5=t2+t3
print(t4)
print(t5)
PRACTICE QUESTIONS
m. t3=(6,7)
t4=t3*3
t5=t3*(3)
print(t4)
print(t5)
n. t1=(3,4)
t2=(‘3’, ‘4’)
print(t1+t2)
PRACTICE QUESTIONS
o. What will be stored in variables a, b, c, d, e, f, g, h after following statements?
perc=(88,85,80,88,83,86) Ans:
a is : ( )
a=perc[2:2]
b is : (80,88,83,86)
b=perc[2:]
c is: (88,85)
c=perc[:2]
(a) T[1][0::2]
(e) True
PRACTICE QUESTIONS
3. Carefully read the given code fragments and figure out the errors that the code may
produce:
print(t[5])
t[0]='A'
(c) t1=(3)
t2=(4,5,6)
t3=t1+t2
print(t3)
PRACTICE QUESTIONS
(d) t1=(3,)
t2=(4,5,6)
t3=t1+t2
print(t3)
(e) t2=(4,5,6)
t3=(6,7)
print(t3 – t2)
(f) t3=(6,7)
t4=t3 * 3
t5=t3 * (3)
t6=t3 * (3,)
print(t4)
print(t5)
print(t6)
PRACTICE QUESTIONS
Reason:
(g) odd=1,3,5 odd is a tuple and it can’t be concatenated with the
print(odd+[2,4,6]) [4] list[2,4,6], also indexing is being done outside the print
statement.
Reason:
(h) t=(‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
1,2,3,4,5 can’t be variable names as no variable name
1,2,3,4,5=t can start with digit.
Reason:
(i) t=(‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
1n, 2n, 3n, 4n, 5n = t 1,2,3,4,5 can’t be variable names as no variable name
can start with digit.
(j) t=('a', 'b','c','d','e') Reason:
x,y,z,a,b=t
No Error. x,y,z,a and b will become 'a', 'b', 'c', 'd', and
'e' respectively.
PRACTICE QUESTIONS
Q.No (4):
(a, b, c, d) = nptl
print("c is:", c)
nptl=(a, b, c, d)
print(nptl[0][0]+nptl[1][1],nptl[1])
Q.No (5): Q.No (6):
tuple_a = a, b tuple1=(‘Python’) * 3
True
Q.No (7):
Find the error. Following code intends to create a tuple with three identical strings. But
even after successfully executing following code(No error reported by python), The len()
returns a value different from 3. Why?
tup1=('Mega')*3
print(len(tup1))
Sol:
This is because tup1 is not a tuple but a string. To make tup1 a tuple it should be
initialized as following:
tup1 = ('Mega',)*3 # notice the "," after 'Mega'
Q.No (8):
print(z[z[z[0]]])
Q.No(9):
Tup1=(1,)*3
Tup1[0]=2
print(Tup1)
Sol:
Error. Because, tuples are immutable and elements can’t be assigned after initialization.
Q.No (10):
Tup1=((1,2),)*7
print(len(Tup1[3:8]))
Sol:
O/P: 4
and print the sum of all these elements from these tuples.
2. Write a Python code to input 'n' number from user, store these numbers in a tuple
and print the maximum, minimum of all these elements from these tuples.