Python Tuple
Python Tuple
Examples:
T1 = ( )
T2 = ( 10 , 30 , 20 , 40 , 60 )
T3 = ( "C" , "Java" , "Python" )
T4 = ( 501 ,"abc", 19.5 )
T5 = ( 90 , )
T6 = ( 'Python' , [2, 4, 6] , (1, 3, 5) )
Tuple indexing:
The indexing and slicing in tuple are similar to lists.
Tuple Functions
Python provides the following built-in functions which can be used with the tuples.
len()
max()
min()
tuple()
sum()
sorted()
index()
count()
len ( ) - In Python, len ( ) is used to find the length of tuple, i.e it returns the number of items in
the tuple.
max() - In Python, max ( ) is used to find maximum value in the tuple.
Min ( ) - In Python, min ( ) is used to find minimum value in the tuple.
sum() - In python, sum(tuple) function returns sum of all values in the tuple. Tuple values must
in number type.
Example:
num = ( 1 , 2 , 3 , 4 , 5 , 6 )
lang = ( ' java ' , 'c' , 'python' ,'cpp' )
length of tuple : 6
Max of tuple : 6
Max of tuple : python
Min of tuple : 1
Min of tuple : c
Sorted ( )
In python, sorted (tuple) function is used to sort all items of tuple in an ascending order.
It also sorts the items into descending and ascending order.
It takes an optional parameter 'reverse' which sorts the tuple into descending order.
num = ( 1 , 3 , 2 , 4 , 6 , 5 )
lang = ( ' java ' , ' c ' , ' python ' , ' cpp ' )
print ( sorted ( num ) )
print ( sorted ( lang ) )
print ( sorted ( num , reverse = True ) )
Output:
(1, 2,3,4,5,6)
( ' c ', ' cpp ', ' java ', ' python ' )
(6,5,4,3,2,1)
tuple (sequence)
The tuple ( ) method takes sequence types and converts them to tuples. This is used to convert
a given string or list into tuple.
Output:
('p','y','t','h','o','n')
(1,2,3,4,5,6)
Count ( )
In python, count ( ) method returns the number of times element appears in the tuple. If the
element is not present in the tuple, it returns 0.
num = ( 1 , 2 , 3 , 4 , 3 , 2 , 2 , 1 , 3 , 4 , 5 , 7 , 8 )
cnt = num . count ( 2 )
print ( " Count of 2 is : " , cnt )
cnt = num . count ( 10 )
print ( " Count of 10 is : " , cnt )
Output:
Count of 2 is : 3
Count of 10 is : 0
Index ( )
In python, index () method returns index of the passed element. This method takes an
argument and returns index of it. If the element is not present, it raises a ValueError.
This method takes two more optional parameters start and end which are used to search index
within a limit.
lang = ( 'p' , 'y' , 't' , 'h' , 'o' ,'n' ,'p' ,'r' ,'o' ,'g' ,'r' ,'a' ,'m' )
print ( " index of t is : " , lang . index ( ' t ' ) )
print ( " index of p is : " , lang . index ( ' p ' ) )
print ( " index of p is : " , lang . index ( ' p ' , 3 , 10 ) )
print ( " index of p is : " , lang . index ( ' z ' ) )
Output:
index of t is : 2
index of p is : 0
index of p is : 6
ValueError : ' z ' is not in tuple.