Python includes many built-in functions that can be executed on tuples. Some of them are decsribed as follows
1. cmp(tuple1,tuple2) : It compares the items of two tuples
2. len(tuples) : It returns the length of a tuple
3. zip(tuple1,tuple2) : It 'zips' the elements from two tuples into a list of tuples
4. max(tuple) : It returns the largest value among the elements in the tuple
5. min(tuple) : It returns the smallest value among the elements in the tuple
6. tuple(seq) : It converts a list into a tuple
Note:
1. zip is a in-built function that takes two or more sequences and "zips" them into a list of tuples where each tuple contains one element from each sequence.
2. When there are different number of elements in the tuple i.e. if the length of the the tuples are not same then the resulting tuple after applying the zip function will have the length of the shorter tuple.
Examples-01: cmp() function
# Python program to demonstrate the
# use of cmp() method
# when a<b
a = 1
b = 2
print(cmp(a, b))
# when a = b
a = 2
b = 2
print(cmp(a, b))
# when a>b
a = 3
b = 2
print(cmp(a, b))
#Output
-1
0
1
Examples-02: len( ), max( ), min( ), tuple( ) Functions
>>> t1=(1,2,3,4,5)
>>> len(t1)
5
>>> max(t1)
5
>>> min(t1)
1
>>> L1=[1,2,3,4,5]
>>> L1
[1, 2, 3, 4, 5]
>>> tuple(L1)
(1, 2, 3, 4, 5)
Examples-03: zip ( ) Function with same size tuple
t1=(1,2,3,4)
t2=("one", "two", "three", "four")
L1=list(zip(t1,t2))
print(L1)
T1=tuple(zip(t1,t2))
print(T1)
#Output
[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
((1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'))
Examples-04: zip ( ) Function with different size tuple
t1=(1,2,3,4)
t2=("one", "two")
L1=list(zip(t1,t2))
print(L1)
T1=tuple(zip(t1,t2))
print(T1)
#Output
[(1, 'one'), (2, 'two')]
((1, 'one'), (2, 'two'))
Examples-05: Matrix Transpose using zip ( ) Function
matrix=[(1,2),(3,4),(5,6)]
print("\n\nGiven Matrix is ")
print(matrix)
print("\n\nTranspose of Matrix is ")
x=list(zip(*matrix))
print(x)
#Output
Given Matrix is
[(1, 2), (3, 4), (5, 6)]
Transpose of Matrix is
[(1, 3, 5), (2, 4, 6)]