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

Tuple 1

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 9

Tuple :

A tuple is an ordered collection of values/items. The items in a tuple can be of any type such as integers,
floating numbers, strings, objects , lists or even tuples.
Elements of a tuple are separated by commas and are enclosed in parenthesis ( ).
Tuples are immutable i.e. values in the tuple cannot be modified which means that Python will create a
new tuple when we make a change in the tuple.

Example : (i) (12, 13, 18, 19, 20) # a tuple storing 5 integers
(ii) ( ‘amit’, ‘sunil’, ‘naman’) # a tuple storing 3 strings
(iii) (12.6, 90.7, 98.5, 80.4) # A tuple storing 4 floating values
(iv) ( [12,14,16], [12,11,9], [8,9,10,100] ) # A tuple containing 3 lists
(v) ( 12, ‘Amit’, *14,17,16,12,19+, 89.5, (2,3,60) ) # A tuple storing heterogeneous data

Difference between a tuple and list :


1. Tuple is immutable whereas list is mutable.
2. Elements of tuple are enclosed in parenthesis i.e. () whereas elements of lists are enclosed in
square bracket i.e. [ ].
3. Example : (12,3,49) is a tuple whereas *12, 90, ‘amit’ + is a list

CREATING A Tuple :
1. A tuple can be created by enclosing the data values with in the parenthesis and separating them
by commas.

Syntax : <tuple_object> = ( value_1, value_2,…, value_n )

Example : (a) T1 = ( 12, 17, 19, 20) # T1 is a tuple/ tuple object containing 4 integers
(b) T2 = () # L2 is an empty tuple

NOTE : A tuple having only one element is known as singleton tuple.


For creating a singleton tuple, one has to write comma after the element within the parenthesis.
Example : T3 = ( 34,)

If we do not write comma after the single element then it is considered as a reference to a single
value.
Example : T3 = (34)
Here T3 is not a tuple rather it is a reference to an integer 34.

2. A tuple can be created by using a built-in-function tuple(). The built in-function tuple() is used to
create a tuple from an existing sequence( list , string ).
Syntax : <tuple_object> = tuple( [ <sequence> ])
Example :
(i) T1 = tuple() # T1 = () created an empty tuple
(ii) T2 = tuple(‘Amit’) # T2 = ( ‘A’, ‘m’, ‘i’, ‘t’ )
(iii) T3 = tuple ( [12,78, 90] ) # T3 = (12,78,90 )

INDEXING :
Each element of the tuple has been assigned an integer value which is known as index or
subscript of that element. There are two kinds of indexing :
1. Forward Indexing or Positive Indexing
2. Backward Indexing or Negative Indexing

Forward Indexing : The indices of the elements are positive Integers, varies from 0 to N-1 from the
beginning, where N is the total number of elements in the tuple. Thus, index of Kth element from the
beginning is K-1.
It is used when we want to traverse a list from the beginning.

Backward Indexing : The indices of the elements are negative integer, varies from -1 to –N from the
end, where N is the total number of elements in the list. Thus, the index of the Kth element from the
end is –K and index of Kth element from the beginning is –(N-K+1).

0 1 2 3 4
T 78 56 34.5 Anil [3,4,5]
Y -5 -4 -3 -2 -1

ACCESSING ELEMENTS OF Tuple :

0 1 2 3 4
T 78 56 34.5 Anil [3,4,5]
-5 -4 -3 -2 -1

The entire tuple can be accessed by using the tuple name. For Example, if we want to play the whole
tuple , then python command is :
print(T)

An individual element can be accessed by using the tuple name followed by index or subscript of that
element within the square bracket [].
Syntax : <tuple_name>[index]

Example : To access the first element of the tuple T containing 5 elements, we shall write T[0] or T[-5].

TRAVERSING A Tuples :
Accessing each element of tuple one by one and then processing them is called traversing.
A tuple can be traversed in two ways :
1. By iterating over the elements of tuple using ‘in’ operator
2. By iterating using the indices of the elements generated by range() function

(i) Traversal of tuple by iterating over the elements of tuple :


Syntax : for <variable_name> in <tuple_name> :
process(<variable_name>)
Example :
(i) T = (23,56,78,90)
for x in T :
print(x)

(ii) T = (23,56,34,12)
S=0
for x in T :
S=S+x
print(“Sum of elements = “, S)

(ii) Traversal of Tuple by using indices of the elements of list :


Syntax : for <index_variable> in range(<length_of_tuple>) :
process( <tuple_name>[index_variable])
Example : (i)
T = (23,56,78,90)
for i in range(len(T)) :
print(T[i])

(ii) T = (23,56,34,12)
S=0
for x in range(len(L)) :
S = S + T[x]
print(“Sum of elements = “, S)

CREATING A TUPLE BY TAKING VALUES FROM USER :


1. Using eval() function
The built-in-function eval() can be used to create a tuple by taking the values from the user
during program execution.
Syntax : <Tuple_object> = eval(<string>]
Example :
(i) S = “12, 23,45,89”
T = eval(S)
print(T)
(ii) T = eval(input(“Enter Marks in 5 subjects : “))
print(T)

Q program to find maximum and minimum value in a list of numbers given by user
Ans.
# A program that will accept a list f numbers from user
# then find the maximum and minimum number in the given list

T = eval(input("Enter a list of numbers : "))

mx = T[0]
mn = T[0]

for x in T :
if mx < x :
mx = x
elif mn > x :
mn = x

print("Maximum value : ", mx)


print("Minimum value : ", mn)

2. Creating a tuple by using concatenation operator(+) :


t1 = ()
n = int(input("How many numbers in list : "))
for i in range(n) :
num = int(input("Enter a number : "))
t1 = t1 + (num,)
print(" Input Tuple : ", t1)

NESTING OF TUPLES :
A tuple within another tuple is called nested tuple.
Example : T1 = (1,2,3)
T2 = (“amit”, “sunil”, “akash”)
T3 = ( T1, T2)
print(T3)
Output :
( (1,2,3), (“amit”, “sunil”, “akash”))

Accessing elements of a nested tuple :


The individual element of nested tuple can be accessed by using tuple_object followed
by two subscript/indices.
In general : <tuple_object>[index1][index2]
Example : To access the second element of first nested tuple in T3 , we shall write T3[0][1]

Q. find the output :


t1 = (1,2,3)
t2 = (4,5,6)
t3 = (t1, t2)
for i in range(2):
for j in range(3):
print(t3[i][j], end = " ")
print()
OUTPUT :
123
456

OPERATIONS ON TUPLES :
1. TUPLE SLICING :
Slicing means retrieving a subset of values from a sequence. Like string and list, slicing can be
applied to tuple also.
Syntax : <tuple_object>[first:last:slice_step]
It retrieves the elements with the index ‘first’ up to the element with index ‘last-1’ skipping
‘Slice_step -1’ element from the specified tuple. The default slice _step value is 1.
Example :
T = (11,22,33,44,55,66,77,88,99)
print(T[2:5])
print(T[:])
print(T[2:8:2])
print(T[:5])
print(T[3:])
print(T[-8:-5])
print(T[-8:-4:2])
print(T[-8:-4:-2])
print(T[-4:-8])
Output :
(33, 44, 55) 0 1 2 3 4 5 6 7 8
(11, 22, 33, 44, 55, 66, 77, 88, 99) 11 22 33 44 55 66 77 88 99
(33, 55, 77) -9 -8 -7 -6 -5 -4 -3 -2 -1
(11, 22, 33, 44, 55)
(44, 55, 66, 77, 88, 99)
(22, 33, 44)
(22,44)
()
()
2. TUPLE CONCATENATION :
Python allows to join two tuples by using concatenation operator ‘+’. New elements can also be
added to an existing tuple using ‘+’ operator.
Example :
T1, T2 = (2,4,6), (1,3,5)
T1 = T1 + T2
print(T1)
Output :
(2,4,6,1,3,5)

3. Tuple Multiplication/Replication using * operator :


The replication operator * can be used to create a tuple by replicating the elements of a tuple or
tuple slice.
Example :
(i) T1 = (11,13,15,17,18)
T2 = T1*3
print(T2)
Output :
(11,13,15,17,18, 11,13,15,17,18, 11,13,15,17,18)
(ii) T1 = (11,13,15,17,18,19,20)
T2 = T1[2:5]*3
Print(T2)
Output :
(15,17,18,15,17,18,15,17,18)

4. Membership operator in and not in :


The membership operator ‘in’ is used to determine whether a value is a member of tuple or not.
It returns ‘True’ if value is present otherwise return ‘False’. The membership operator ‘not in’ returns
True if value is not present otherwise return False.
Example :
T1 = (11,22,33,44,55,66,77)
print( 22 in T1)
print( 45 in T1)
print(110 not in T1)
Output :
True
False
True
Tuple COMPARISON :
One can compare two tuples by using relational operator <, >, <=, >=, != and ==. During
Comparison, elements of first tuple is compared with corresponding elements of second tuple in
lexicographical ( alphabetical ) order.
Example : (i)
>>> T1 , T2 = (10,20,30), (10,20,30)
>>> T3 = (10, (20,30) )
>>> T1 == T2
True
>>> T1 == T3
False
NOTE :
(i) Two tuple are said be equal if they have same number of elements and corresponding
elements are tuple should be equal.

(ii) <, >, <= and >= operators cannot be applied to compare two values of different types i.e <
cannot be applied to compare an int type value with a tuple type object.
Example : >>> (1,2,3) < (1,[2,3])
TypeError

BUILT-IN METHODS AND FUNCTIONS :


1. len() : It is a built-in function that returns the size of the tuple i.e. total number of elements
in the tuple.
Syntax : len(<tuple_object>)

Example : T = ( 1,2,3,4,5)
N = len(T)
print(“Size of tuple : “, N)
2. count() :
It is a built-in method that returns the number of times an element appears in the tuple.
Syntax : <list_object>.count(<item>)
Example :
T = (1,2,3,4,3,2,3,5,4)
N = T.count(3)
print( “ No of times 3 appears : “, N)
3. any() :
It is a built-in function that returns True if the tuple passed to it as an argument is non
empty otherwise return False.
Syntax : any(<tuple_object>)
Example:(i)
T = ()
B1 = any(T)
print(B1)
Output :
False
Example:(ii)
T = (23,45,67)
B1 = any(T)
print(B1)
Output :
True
4. max() : It is a built-in function that returns the maximum value in the tuple passed as an
argument to it.
Syntax : max(<tuple_object>)
Example :
T1 = (3,4,5,2,6,1)
Mx = max(T1)
print(“Maximum value = “, Mx)
5. min() : It is a built-in function that returns the minimum value in the tuple passed as an
argument to it.
Syntax : min(<tuple_object>)
Example :
T1 = (3,4,5,2,6,1)
Mn = min(T1)
print(“Maximum value = “, Mn)
6. sorted() : It is a built-in function that returns a list containing elements of tuple in
ascending order.
Syntax : sorted(<tuple_object>)
Example : T = (2,4,1,5,3)
L = sorted(T)
print(L)
Output :
[1,2,3,4,5]
7. index() : It is a built-in method that returns the first index of the item passed to it as an
argument if item is present in the tuple. It item is not present in the tuple then it gives an
error mesaage : x not in tuple
Syntax : <tuple_object>.index(item)
Example :
T = (2,3,4,5,4,6,4)
P = T.index(4)
print(“ 4 is present at position “, P+1)
Output :
4 is present at position 3
Deleting a tuple :
The del statement is used to delete a tuple.
Syntax : del <tuple_object>

Example : T = (2,3,4,5)
del T # Tuple T is removed from memory
print(T) # ERROR as T does not exist in memory

You might also like