TUPLE
TUPLE
1. A tuple is a sequence of immutable objects. That is, you can change the value
of one or more items in a list; you cannot change the values in a tuple.
2. Tuples use parenthesis to define its elements. Whereas lists use square brackets.
Creating a Tuple:
Syntax: Tup1=(val1,val2,….)
Where val (or values) can be an integer, a floating number, a character, or a string.
Examples:
1) Tup1=( )
#creates an empty tuple.
print(Tup1)
output:
Output:
3) Tup1=(1,2,3,4,5)
#creates a tuple of integers print (Tup1)
Tup2=(„a‟,‟b‟,‟c‟,‟d‟)
Tup3=(“abc”,”def”,”ghi”)#creates a tuple of
strings print(Tup3)
Tup4=(1.2,2.3,3.4,4.5,5.6)
Tup5=(1,”abc”,2.3,‟d‟)
Output:
1,2,3,4,5
„a‟,‟b‟,‟c‟,‟d‟
„abc‟,‟def‟,‟ghi‟
1.2,2.3,3.4,4.5,5.6
1,‟abc‟,2.3,‟d‟
Example :
1) Tup1=(1,2,3,4,5,6,7,8,9,10)
print(“Tup[3:6]=”,Tup1[3:6])
print(“Tup[:8]=”,Tup1[:4])
print(“Tup[4:]=”,Tup1[4:])
print(“Tup[:]=”,Tup1[:])
Output:
Tup[3:6]=(4,5,6)
Tup[:8]=(1,2,3,4)
Tup[4:]=(5,6,7,8,9,10)
Tup[:]=(1,2,3,4,5,6, 7,8,9,10)
1) Tuple =(1,2,3,4,5.5,‟str‟)
Input:
1. print tuple
2. print tuple[5]
3. print tuple[1:5]
Output:
1.1,2,3,4,5.5,‟str‟
2.‟str‟
3.2,3,4,5.5
Updating tuples:
As we all know tuples are immutable objects so we cannot update the values but
we can just extract the values from a tuple to form another tuple.
Example:
1) Tup1=(1,2,3,4,5)
Tup2=(6,7,8,9,10)
Tup3=Tup1+Tup2
print(Tup3)
Output
(1,2,3,4,5,6,7,8,9,10)
2) Tup1=(1,2,3,4,5)
Tup2=(„sree‟,‟vidya‟,‟ram‟)
Tup3=Tup1+Tup2
print(Tup3)
Output:
(1,2,3,4,5,‟sree‟,‟vidya‟,‟ram‟)
Hence there is another option to delete a single element of a tuple i.e..,you can
create a new tuple that has all elements in your tuple except the ones you don‟t
want.
Example:
1) Tup1=(1,2,3,4,5)
del Tup1[3]
print Tup1
Output:
del Tup1[3]
2) however, you can always delete the entire tuple by using del statement.
Tup1=(1,2,3,4,5)
del Tup1
print Tup1
Output:
Like strings and lists,you can also perform operations like concatenation,
repetition,etc. on tuples. The only difference is that a new tuple should be
created when a change is required in an existing tuple.
Length len((1,2,3,4,5,6)) 6
print(i,end=‟ „)
print(Tup1>Tup2)
Maximum max(1,0,3,8,2,9) 9
Minimum min(1,0,3,8,2,9) 0
Ex:
Input:
Tup1= (1,2,3,4,5)
Output:
2) Concatenation:
Ex:
Input:
Tup1=(1,2,3,4
)
Tup2=(5,6,7)
print tup1+tup2
Output:
(1,2,3,4,5,6,7)
3) Repetition:
Ex:
Input:
Tuple1=(„my‟)
print tuple1*3
Output:
(„my‟,‟my‟,‟my‟)
4.Membership:
Ex:
Input:
Tuple1=(1,2,3,4,6,
7)
5.Iteration:
Ex:
Input:
For i in (1,2,3,4,5,6,7,8,9,10):
print (i,end=‟ „)
Output:
1,2,3,4,5,6,7,8,9,10
6.Comparison:
Ex:
Input:
Tup1 = (1,2,3,4,5)
Tup2 =(6,7,8,9,10)
print(Tup1<tup2)
Output:
True
7. Maximum:
Ex:
Input:
Max(1,2,6,5,4
)
Output:
8. Minimum:
Ex:
Input:
Min(1,2,3,4,5
)
Output:
Convert to tuple:
Ex:
Input:
Tuple(“vidya”)
Output: („v‟,‟i‟,‟d‟,‟y‟,‟a‟)