0% found this document useful (0 votes)
21 views9 pages

XI CS Tuple

Uploaded by

n73928957
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)
21 views9 pages

XI CS Tuple

Uploaded by

n73928957
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/ 9

TUPLE

INTRODUCTION
A tuple is a collection which is ordered and immutable (We cannot change elements of a tuple in
place). Elements of a tuple are enclosed in parenthesis (round brackets) and are separated by
commas. Tuples can store a sequence of values belonging to any type. Tuples allows duplicate
members.
Ex:- T1 = ( ) # Empty Tuple
T2 = (4,5,6) # Tuple of integers
T3 = (1.5,4,9) # Tuple of numbers
T4 = (‘x’, ‘y’, ‘z’) # Tuple of characters
T5 = (‘a’,1.5,’KVS’,45) # Tuple of mixed values
T6 = (‘KVS’, ‘NVS’, ‘EMRS’) # Tuple of strings
>>>t2 = (10,) # Single element tuple
Note:- comma is necessary in single value tuples. Without a comma it will be a value, not a tuple.
>>>t3=(10,20,30,40,50) # Long tuple
>>>t4=(6,(4,5),9,7) # Nested Tuple
● tuple( ) function is used to create a tuple from other sequences.
● Indexing of tuple is similar to indexing of list.
● Difference between List and Tuple
S. No. List Tuple
01 Elements are enclosed in square brackets Elements are enclosed in parenthesis
i.e. [ ] i.e. ( )
02 It is mutable data type It is immutable data type
03 Iterating through a list is slower as Iterating through a tuple is faster as
compared to tuple compared to list

TRAVERSING A TUPLE
Traversing a tuple means accessing and processing each element of it. A tuple can be traversed using
a loop.
Ex:- >>> T1=(2,4,6,8,10) Output: 2
>>> for a in T1: 4
print(a) 6
8
10
ACCESSING TUPLES
Elements of a tuple can be accessed using Indexing and Slicing, same as in string and list.
if T1= (‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’):

54
Elements C 0 M P U T E R
+ index Value 0 1 2 3 4 5 6 7
- Index Value -8 -7 -6 -5 -4 -3 -2 -1

>>> T1[2] #WILL ACCESS ‘M’


>>> T1[-3] #WILL ACCESS ‘T’
>>> T1[1:7:1] #WILL ACCESS ‘OMPUTE’

OPERATORS IN TUPLE
Operation Name Description Example
Concatenation (+) Joining of two or more tuples is >>>t1 = (1, 2, 3)
called concatenation >>>t2 = (8, 9, 11)
Python allows us to join tuples >>>t1+t2
using concatenation operator (+) OUTPUT :
(1, 2, 3, 8, 9, 11)
(#concatenates two tuples)
>>>t1 = (1, 2, 3)
>>>t2 = (8, 9, 11)
>>>t3 = t1+t2
(#Created new tuple)
OUTPUT :
(1, 2, 3, 8, 9, 11)
Concatenation operator can also
be used for extending an
existing tuple.
>>>t1 = (1, 2, 3)
>>>t1 = t1 + (7,8,9)
>>>t1
It is used to repeat elements of a
>>>h1 = (‘H’ , ‘M’) >>>h1 * 3 (‘H’
Repetition (*) tuple. Repetition operation is
, ‘M’, ‘H’ , ‘M’, ‘H’ , ‘M’)
denoted by Symbol (*)
Membership The ‘in’ operator checks the >>>h1 = (‘H’ , ‘M’)
presence of element in tuple. If >>>’H’ in h1
the element is present it returns True
True, else it returns False. >>>’m’ not in h1
55
The not in operator returns True True
if the element is not present in
the tuple, else it returns False.
Slicing It is used to extract one or more >>>t1 = (1, 2, 3, 7, 8, 9)
elements from the tuple. Like >>>t1[2:4]
string and list, slicing can be (3, 7)
applied to tuples also. >>>t1 =(10, 20, 30, 40, 50,
60, 70, 80)
>>>t1[2 : 7]
(30, 40, 50, 60, 70)
>>>t1[ : 5]
(10, 20, 30, 40, 50)
>>>t1[: : -1]
(80, 70, 60, 50, 40, 30, 20, 10)

Tuple Methods and Built-in Functions

Method Name Description Example

>>>t1 =(10,20,30,40,50, 60, 70,


This method returns the length of 80)
len( ) tuple or the number of elements in
the tuple. >>>len(t1)
8
>>>t1 = tuple()
>>>type(t1)
<class ‘tuple’>

This function creates an empty tuple >>>t1 = tuple(‘python’) #string


tuple( ) or creates a tuple if a sequence is >>>t1
passed as argument. (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)

>>>t1 = tuple([1,2,3]) #list


>>>t2
(1, 2, 3)

56
>>>t1 = tuple(range(7))
>>>t1
(0, 1, 2, 3, 4, 5, 6)
>>>t1=tuple(“tuples in python”)
This function returns the frequency
count( ) >>>t1.count(‘p’)
of an element in the tuple.
2
>>>t1=tuple(“tuples in python”)
>>>t1.index(‘n’)
This function returns the index of the 8
index( ) first occurrence of the element in the
given tuple. >>>t1=tuple(“tuples in python”)
>>>t1.index(‘f’)
ValueError: tuple.index(x): x not in tuple
>>>t1 = (‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
This element takes tuple as an >>>sorted(t1)
argument and returns a sorted list.
sorted( ) [‘e’, ‘l’, ‘p’, ‘s’, ‘t’, ‘u’]
This function does not make any
change in the original tuple. >>>t1
(‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
>>>t1 = (3, 8, 4, 10, 1)
>>>min(t1)
This function returns the minimum or 1
min( )
smallest element of the tuple. >>>t1 = (‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
>>>min(t1)
‘e’
>>>t1 = (3, 8, 4, 10, 1)
>>>max(t1)
This function returns the maximum 10
max( )
or largest element of the tuple. >>>t1 = (‘t’, ‘u’, ‘p’, ‘l’, ‘e’, ‘s’)
>>>max(t1)
‘u’
>>>t1 = (3, 8, 4, 10, 1)
This function returns the sum of the
sum( ) >>>sum(t1)
elements of the tuple.
26

57
MIND MAP OF TUPLE

Multiple Choice Question


Q.1 What type of error is returned by following code :
a=(“Amit”, “Sumit”,”Ashish”,”Sumanta”)
print(a.index(“Suman”))
(a) Syntax Error (b) Value Error (c) Type Error (d) Name Error
Q.2 What is the length of the given tuple? >>> t1=(1,2,(3,4,5))
(a) 1 (b) 2 (c) 3 (d) 4
Q.3 Which of the following statements will return an error. T1 is a tuple.
(a) T1 + (23) (b) T1 + [3] (c) Both (a) & (b) (d) None
Q.4 What is the output of following code?
>>> t1=(1,2,(3,4,5,2))
>>> print(len(t1[2]))
(a) 1 (b) 2 (c) 3 (d) 4
Q.5 Which of the following is not a tuple?
(a) P = 1,2,3,4,5 (b) Q = (‘a’, ‘b’, ‘c’) (c) R = (1, 2, 3, 4) (d) None
Q.6 Which of the following is/are features of tuple?
(a) Tuple is immutable (b) Tuple is a sequence data type.
(c) In tuple, elements are enclosed in Parenthesis (d) All of the above
Q.7 Which of the following is not a function of tuple?
(a) update( ) (b) min( ) (c) max( ) (d) count( )
58
Q.8 Which of the following is/are features of tuple?
(a) Tuple is immutable (b) Tuple is a sequence data type.
(c) In tuples, elements are enclosed in Parenthesis. (d) All of the above
Q.9 Which of the following is a tuple with a single element?
(a) t = (1,) (b) t = 1, (c) Both (a) & (b) (d). None of the above
Q.10 Rahul wants to delete all the elements from the tuple t, which statement he should use
(a) del t (b)clear() (iii) t.remove() (iv) None of these

ANSWERS OF MCQ
(1) b, (2) c, (3) c, (4) c, (5) a, (6) d, (7) a, (8) d, (9) c, (10) a
Competency Based Question
Q.1 Discuss the utility and significance of Tuples, briefly.
Ans. It is a type of array. It plays a very important role in python. In python it is an immutable type
of container which stores any kind of data types. It is short in memory size in comparison to
lists.
Q.2 Lists and Tuples are ordered. Explain.
Ans. Lists and Tuples are ordered sequences as each element has a fixed position.
Q.3 Write the output of the following.
a=(23,34,65,20,5)
print(a[0]+a.index(5))
Ans. 27
Q.4 Create a tuple names as given here:
names = ('JAI', 'RAM', 'MAMTA', 'KAPIL', 'DINESH', 'ROHIT') Write proper code for getting:
('MAMTA', 'KAPIL', 'DINESH')
Ans. print(names [2 : 5 ])
Q.5 T1=(1,2) & T2=(“KV”,)
print(T2*2)
Ans. (‘KV’,’KV’)
Q.6 T1=(45,67,98)
T1=T1+(1,2,3)
print(T1)
Ans. (45,67,98,1,2,3)
Q.7 Consider the following tuple and write the code in python for the following statements:
T1=(12,3,45,’Hockey’,’Anil’,(‘a’,’b’))
(a) Display the first element of ‘T1’ (b) Display the last element of ‘T1’
(c) Display ‘T1’ in reverse order. (d) Display ‘Anil’ from tuple ‘T1’
(e) Display ‘b’ from tuple
59
Ans. (a) print(T1[0]) (b) print(T1[-1]) (c) print(T1[ : :-1]) (d) print(T1[4])
(e) print(T1[5][1])
Q.8 What is unpacking Tuple?
Ans. It allows a tuple of variables on the left side of the assignment operator to be assigned
respective values from a tuple on the right side. The number of variables on the left should be
the same as the number of elements in the tuple.
Q.9 What are nested tuples?
Ans A tuple containing another tuple in it as a member is called a nested tuple, e.g., the tuple
shown below is a nested tuple:
Employees = (4580,'Rahul', (82,67,75,89,90)) # nested tuple
Q.10 for i in tuple(“KVS”):
print(i+i)
Ans. KK
VV
SS
Very short Questions
Q.1 T1=(“Hockey”, “Cricket”, ‘Football’)
print(max(T1))
print(min(T1))
Ans. Hockey
Cricket
Q.2 What will be the output of the following Python Code?
tp = (5,)
tp1 = tp * 2
print(len(tp1))
Ans. 2
Q.3 Type Error occurs while statement 2 is running. Give reason. How can it be corrected?
>>> tuple1 = (5) #statement 1
>>> len(tuple1) #statement 2
Ans. Because tuple1 is an integer not a tuple. So, we cannot find the length of the integer. If you
want to make tuple then you should write ( 5, )
Q.4 How to create an empty tuple? Also create a single element tuple.
Ans. t=( ) or t=tuple( ) single element tuple: t=(10,)
Q.5 Write a program that inputs two tuples and creates a third, that contains all elements of the
first followed by all elements of the second.
60
Ans. tup1 = eval(input("Enter First tuple :-"))
tup2 = eval(input("Enter second tuple :-"))
tup3 = tup1 + tup2
print(tup3)
Q.6 T1=('A',['B','D'],'C')
T1[1][1]='C'
print(T1)
Ans. ('A', ['B', 'C'], 'C')
Q.7 What is the difference between a List and a Tuple?
Ans.
List Tuple
Elements are enclosed in square brackets i.e. [ ] Elements are enclosed in parenthesis i.e. ( )
It is mutable data type It is immutable data type
Iterating through a list is slower as compared Iterating through a tuple is faster as
to tuple compared to list

Q.8 Which error is returned by the following code:


T = (10,20,30,40,50,60,70)
print(T[20])
Ans. Index Error : tuple index out of range
Q.9 Write a statement to print 30 from the given tuple.
T=(“Seven”,[1,2,3],(20,30,40),”eight”)
Ans. print(T[2][1])
Q.10 Write a program to create a tuple and find sum of its alternate elements?
Ans. T = (10,23,30,65,70)
sum = 0
for a in T[0:5:2]:
sum = sum + a
print(sum)
Long Question
Q.1 Write a program to input n numbers from the user. Store these numbers in a tuple. Print the
maximum and minimum number from this tuple.
Ans. tup= ()
while True :

61
n = int(input("Enter a number :- "))
tup += (n,)
ch = input("To quit enter y/Y =")
if ch == "y" or ch=="Y":
print(tup)
print("Max :-",max( tup ))
print("Min :-",min( tup ))
break
Q.2 Write a program to count vowels in a tuple?
Ans. T = tuple(input("Enter Name :"))
print(T)
v=0
for ch in T:
if ch in ['a','e','i','o','u']:
v=v+1
print("No. of vowels : ",v)
Q.3 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 = perc[2:2] ()
b = perc[2:] (80, 88, 83, 86)
c = perc[:2] (88, 85)
d = perc[:-2] (88, 85, 80, 88)
e = perc[-2] 83
f = perc[2:-2] (80, 88)
g = perc[-2:2] ()
h = perc[:] (88, 85, 80, 88, 83, 86)

Case Study based question


Q.1 Ram tried to create tuple t=(1,2,3) and wanted to change the value using t[1]=10 it showed
error, Why.
Ans. Due to Immutable data type he cannot change
Q.2 Laxman write some code >>>T1=(10) #STM1 and >>>len(T1) #STM2 when he executes
statements which error will occur and how he corrects it.
Ans. Type error will occur, corrected code will be T1=(10,)

62

You might also like