0% found this document useful (0 votes)
23 views

CH - 12 TUPLES

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)
23 views

CH - 12 TUPLES

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/ 55

CHAPTER - 12

TUPLES

TOPICS
INTRODUCTION
 Tuple is an another sequence data type.

 Tuple is used to store sequence of values belonging to any type.

Advantages:

 It supports Immutability.

 It supports heterogeneous.

 It supports multi-dimensional.

 It is very faster than list.


DIFFERENCE BETWEEN LIST AND TUPLES
LIST TUPLE
(i) Lists are Mutable data type. (i) Tuple is Immutable data type.
(ii) A List can be create by using [ ]. (ii) A tuple can be create by using ( ).
(iii) A list is dynamic. It can be shrink (iii) Tuple also Dynamic. But, we can
or expands whenever we delete or assign memory to tuple only once.
insert elements.
(iv) In list we can add or sort or (iv) We can’t add or sort or remove
remove elements. element in tuple.
CREATING TUPLES IN PYTHON
 In Python Tuple can be created using Parentheses ( ).

 Every Item or element has index that ranges from 0 to n-1.

(i) To create an Empty Tuple:

 An empty Tuple can be create by two ways. They are:

(i) By Assigning Empty Parentheses ( ) to a variable.

(or)

(ii) By Assigning tuple( ) method to a variable.

Example:

A=( ) (or) M= tuple( )


CREATING TUPLES IN PYTHON
(ii) Single Element Tuple:

 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:

Consider the following tuple -4 -3 -2 -1

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

[2] (or) [-3] = 30 45


[0] [1]
ACCESSING ELEMENTS OF TUPLE
 Tuple elements can be accessed in two ways they are:

(i) Accessing an Individual element.

(ii) Traversing a Tuple element using Loop.

(i) Accessing an Individual element:

 It allows user to access elements from tuple by using particular index value.

Syntax:

Tuple_Variable_Name[index_value]

Example:
(ii) Traversing a Tuple:

 Traversing means accessing elements of a tuple one by one using loop.

 “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:

 Slicing means "a part of“

 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.

How to apply Slicing in List?

Syntax: Variable_Name[start:end:step]

Where,

Start -> It is starting index from where we want to start the extraction.

end ->It is the index upto which we want 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:

i. Tuple[Start:end] Extract elements from start to end -1.

ii. Tuple[Start:] Extract elements from start to end.


iii. Tuple[:end] Extract elements from 0 th index to end-1

iv. Tuple[-Start:] Extract elements from start to end-1

v. Tuple[:-end] Extract elements from 0th index to end-1

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:

(i) Print the value of 3rd element from the beginning .

(ii) Print the value of 2nd element from Back.

(iii) To Print Pineapple.


TUPLE OPERATIONS
 Tuples operations are used to manipulate the tuple.

 Python offers following tuple operators to do the manipulation

(i) Concatenate operator.

(ii) Replication operator.

(iii) Membership operators.

(iv) Comparison operators.


(i) Joining Tuple or Concatenate operator
 Joining of two or more Tuple operands is called "Concatenation".

 The '+‘(plus) operator is used to concatenate tuples together.

 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.

 When we extend a tuple using concatenation a new tuple is created.

Example - 1:

#single element is appended to tuple T

Example – 2:

#more than one elements are appended


(ii) Replication operator
 The replication operator is depicted by symbol *

 It is used to repeat elements of a tuple.

 The repetition operator requires the first operand to be a tuple and the second
operand to be an integer only.

 Syntax: Tuple * Number (or) Number * Tuple

Some valid Examples: Some Invalid Example:


(iii) MEMBERSHIP OPERATORS
 The membership operator check whether a given element is present or not in a tuple

 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:

(i) Using tuple unpacking.

(ii) Using the constructor functions of list() and tuple().


(i) Using Tuple Unpacking
 Tuples are immutable to change a tuple we would need to first unpack it, change

values and then again repack it.

(i) Unpack -> (ii) change -> (iii) Repack

Example:

>>> T=(10,20,30,450)
a=10 b=20 c=30 d=450

>>> a,b,c,d=T Unpack the tuple

>>> d=40 Change the value

>>> T=(a,b,c,d) Again the Pack the tuple.

>>> 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( )

(ii) Make changes in desired element on the list.

(iii) Again convert list into tuples using tuple() function.

>>> 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)

>>> del tp1[0]

Error (type error)

 But we can delete a complete or entire tuple with del.

Example:

>>> del tp1

>>> tp1

Error (not defined)


TUPLE FUNCTIONS AND METHODS
 The following are built-in functions and methods of Tuple.

(i) len() (ii) min() (iii) max()

(iv) sum() (v) tuple() (vi) sorted()

(vii) t.index() (viii) t.count()


(i) len( )
➢ This function returns the total number of elements in Tuple, passed as argument to len
method.

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.

 If given element is not in the Tuple, Python generates ValueError exeception.

Syntax:

Tuple_Variable_Name.index(Value)

Example:
(viii) t.count()
 This method returns the count of an element in a given tuple.

 If given element is not in the Tuple, Python returns 0.

Syntax:

Tuple_Variable_Name.count(element)

Example:
PRACTICE QUESTIONS
1. Why are tuples called immutable types?

2. Write the difference between List and tuples with example.

3. What are different ways of creating tuples?

4. What values can we have in tuple? Do they all have to be the same type?

5. How are individual elements of tuples accessed?

6. Does the slice operation always produce new tuple?

7. How is an empty tuple created?

8. How can you add an extra element to a tuple?

9. What is the difference between (30) and (30,)?

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:

f. What will be the values and types of variables a, b, c, d, e, f, p, q, r, s, t after executing


part e above if t1 contains (1, 2.0, 3, 4.0, 5) ?

Sol:
PRACTICE QUESTIONS
g. >>> t2 = ('a')

>>> type (t2)

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]

d=perc[:-2] d is: (88,85,80,88)

e=perc[-2:] e is: (83,86)


f=perc[2:-2]
f is: (80,88)
g=perc[-2:2]
g is: ( ) #because index -2 is after index 2.
h=perc[:]
h is: (88,85,80,88,83,86)
PRACTICE QUESTIONS
2. What does each of the following expressions evaluate to? Suppose that T is tuple
containing: T=("These", ["are", "a", "few", "words"],"that" , "we", "will", "use")

(a) T[1][0::2]

(b) “a” in T[1][0]


Answers:
(c) T[:1] + T[1]
(a) ['are', 'few']
(d) T[2: :2]

(e) T[2][2] in T[1] (b) True

(c) TypeError: can only concatenate tuple (not "list") to


tuple.

(d) ('that', 'will')

(e) True
PRACTICE QUESTIONS
3. Carefully read the given code fragments and figure out the errors that the code may
produce:

(a) t=('a', 'b', 'c', 'd', 'e')

print(t[5])

(b) t=('a', 'b', 'c', 'd', 'e')

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):

What would be the output of the following code if:

nptl=("Hello", "Nita", "How’s", "life?")

(a, b, c, d) = nptl

print("a is:" ,a)

print("b is:" ,b)

print("c is:", c)

print("d is:" ,d)

nptl=(a, b, c, d)

print(nptl[0][0]+nptl[1][1],nptl[1])
Q.No (5): Q.No (6):

Predict the output: predict the output:

tuple_a = a, b tuple1=(‘Python’) * 3

tuple_b = (‘a’, ’b’) print(type(tuple1))

print(tuple_a = = tuple_b) O/P:

O/P: <class ‘str’>

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):

Predict the output: O/P:


x=(1,(2,(3,(4,)))) 2
print(len(x)) 2
print(x[1][0]) False
print(2 in x) 3
y=(1,(2,(3,) 4 ), 5 ) 3
print(len(y)) 55
print(y[2]+50) (1,(2,),1)
z=(2,(1, (2,), 1), 1)

print(z[z[z[0]]])
Q.No(9):

What will the following code produce?

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):

What will the following code produce?

Tup1=((1,2),)*7

print(len(Tup1[3:8]))

Sol:
O/P: 4

Reason: Because, tuple’s last index is 6, so length of elements from 3 to 6 would be 4,


also each element of tuple is (1,2)
PRACTICE QUESTIONS
1. Write a Python code to input 'n' number from user, store these numbers in a tuple

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.

3. Write a Python program to count frequency of elements in Tuple.


THE END

You might also like