Nothing Special   »   [go: up one dir, main page]

09.Tuple Datatype

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Tuple:

 Tuple is exactly same as list except that it is immutable, i.e once we create
tuple object then we cannot perform any changes in that object. Hence,
tuple is read only version of list.
 If our data is fixed and never changes then we should go for tuple.
 Insertion order is preserved.
 Duplicates are allowed.
 Heterogeneous objects are allowed.
 Tuple supports both positive and negative index.
 We can represent tuple elements within () with comma operator.
 Parentheses are optional but recommended to use.

Ex:
t=10,20,30,40
print(t)
print(type(t))

Ex: t=()
print(t)
print(type(t))

Note: We have to special care about single valued tuple. Compulsory the value
should ends with comma, otherwise it is not treated as tuple.

Ex: t=(10)
print(t)
print(type(t))
Ex: t=(10,)
print(t)
print(type(t))

Creating Tuple:
1. t=() Creation of empty tuple.
2. t=(10,20,30) or t=10,20,30 Creation of multi value tuple.
3. By using tuple() function Ex:
l=[12,33,44]
print(type(l))
print(l)
t=tuple(l)
print(type(t))
print(t)
Accessing elements of tuple:
We can access either by index or by slice operator.

By using index:
t=(10,20,30,40)
print(t[3])
print(t[-2])

By using slice:
t=(10,20,30,40,45,33,22)
print(t[2:5])
print(t[2:100])
print(t[::5])

Ex:
t1=(10,20,30,40,50)
print(t1[0])
print(t1[2:4])
print(t1[:4])
print(t1[2:])
print(t1[:])
print(t1[2:10])
#print(t1[10])
#IndexError: tuple index out of range
print(t1[-3])
print(t1[-4:-2])
print(t1[:-3])
print(t1[-3:])
print(t1[:])
#print(t1[-9])
#IndexError: tuple index out of range

Using while loop:


t=(10,20,30,40,45,33,22)
i=0 while i<len(t):
print(t[i])
i=i+1
Using for loop:

t=(10,20,30,40,45,33,22)
for x in t:
print(x)
Ex:
t1=(10,20,30)
t2=(10,20,30)
t3=t1
print(id(t1))
print(id(t2))
print(id(t3))
# checking the data only but not address
print(t1==t2)
print(t1==t3)
print(t3==t2)
# checking the memory address
print(t1 is t2)
print(t1 is not t2)
print(t1 is t3)
print(t1 is not t3)
# checking data is available or not
print(10 in t1)
print(100 in t2)
print(100 not in t2)

Ex: Nested Tuple


my_tuple=("mouse", (1,2,3), ('a','b'),"anu")
print(my_tuple)
matrix = ((1,2,3),(4,5,6),(7,8,9))
print(matrix[1])
print(matrix[1][1])
print(matrix[2][0])

Tuple vs immutability
Once we create tuple, we cannot change its content.
Hence tuple objects are immutable.
Ex:
t=(10,20,30,60)
t[1]=45
#TypeError: ‘tuple’ object does not support items assignment

Mathematical operators for tuple:


We can apply + and * operators for tuple.
Concatenation operator(+):
Ex:
t1=(10,20,30)
t2=("abc","xyz")
t3=t1+t2 print(t3)

Multiplication operator or repetition operator (*):


Ex: t1=(10,20,30)
t2=t1*3
print(t2)

Ex:
tup1 = (10, 20,30)
tup2 = ('satish', 'lokesh')
tup3 = tup1 + tup2
print(tup3)
print(len(tup3))
tup4 = tup1*3
print(tup4)
print(len(tup4))

# tuple is immutable so modifications are not allowed


t1=(10,20,30)
#t1[1]=100
TypeError: 'tuple' object does not support item assignment
#t1.insert(1,100)
AttributeError: 'tuple' object has no attribute 'insert'
print(t1)
#conversion of tuple to list data do the modifications
t1=(10,20,30)
t2 = t1+(40,50)
print(t2)
l1 = list(t2)
l1.append(60)
l1.insert(2,6)
t3 = tuple(l1)
print(t3)

#conversion of list to tuple


l= [10,20,30]
t= tuple(l)
print(t)

# conversion of tuple to String


tup = ('s','a','t','i','s','h')
str = ''.join(tup)
print(str)
To delete the tuple:
To delete tuple using del operator.
Syntax:
del tuplename
Ex: t=(10,20,30)
print(t)
del t
print(t)

Ex: Compare two tuples using > operator.


t1=(10,20,30,40)
t2=(10,20,40,60)
if t1>t2:
print("tuple-1 is big")
else:
print("tuple-2 is big")

Important functions in tuple:


len(): - To return number of elements present in the tuple.
Ex:
t=(10,20,30,40)
print(len(t)) #4

count(element): - To return number of occurrences of given element in the tuple.


Ex:
t=(10,20,10,10,20)
print(t.count(10)) #3

index(element): - Returns index of first occurrence of the given element. If the


element is not available then we will get ValueError.
Ex:
t=(10,20,10,10,20)
print(t.index(10)) #0
print(t.index(30)) #ValueError: tuple.index(x): x not in tuple.

sorted(): - To sort the elements based on natural sorting order.


Ex:
t1=(10,50,23,40)
t2=sorted(t1)
print(t1)
print(t2)
Ex: for descending order
t1=(10,50,23,40)
t2=sorted(t1,reverse=True)
print(t1)
print(t2)

min(): - It returns smallest value in the tuple.


max(): - It returns highest value in the tuple.
Ex:
t1=(10,50,23,40,22,55,43)
print("Smallest value=",min(t1))
print("Highest value=",max(t1))

Tuple packing and un-packing Packing:


Group the different individual values into tuple.
Ex: a,b,c,d=10,20,30,40
t=a,b,c,d
print(type(t))
print(t)

Un-Packing:
Splitting a tuple into individual elements.
Ex:
t=(13,20,35,44)
a,b,c,d=t
print("a={} b={} c={} d={}".format(a,b,c,d))

Note: At the time of tuple unpacking the number of variables and number of
values should be same, otherwise we will get ValueError.
Ex:
t=(10,20,30,40)
a,b,c=t
#ValueError: too many values to unpack Ex:

Ex:
tuplex = (2, 4, 5, 6, 2, 3, 4, 4, 7)
print(tuplex)
count = tuplex.count(4)
print(count)
tuplex = tuple("satish")
print(tuplex)
index = tuplex.index("a")
print(index)
index = tuplex.index("s", 3)
print(index)
index = tuplex.index("t", 1,3 )
print(index)
#if item not exists in the tuple return ValueError Exception
#index = tuplex.index("y")

Ex:
t1=(10,20,30)
print(min(t1))
print(max(t1))
t1=('satish','lokesh','rajesh')
print(min(t1))
print(max(t1))

Ex: Write a program to take tuple of numbers from the keyboard and print sum
and average.
t=eval(input("Enter some tuple of numbers:"))
sum=0
l=len(t)
for x in t:
sum=sum+x
print("Sum=",sum)
print("Average=",sum/l)
Difference between List and Tuple:
List and Tuple are exactly same except small difference: List objects are mutable
where as Tuple objects are immutable.

In both cases insertion order is preserved, duplicate objects are allowed,


heterogenous objects are allowed, index and slicing are supported.

List Tuple
1. List is a group of comma separated 1. Tuple is a group of comma separated
values within square brackets and values within parenthesis and
square brackets are mandatory. parantesis are optional. Ex:
Ex: l=[10,20,30,40] t=(10,20,30,40) t=10,20,30,40

2. List objects are mutable. i.e, once we 2. Tuple objects are immutable. i.e,
creates list object we can perform any once we creates tuple object we cannot
changes in that object. changes its content.
Ex: l[1]=70 Ex: t[1]=70
ValueError: tuple object does not
support item assignment.

3. If the content is not fixed and keep 3. If the content is fixed and never
on changing then we should go for changes then we should go for Tuple.
List.

4. List objects cannot used as keys for 4. Tuple objects can be used as keys for
dictionaries because keys should be dictionaries because keys should be
Hashtable and immutable. Hashtable and immutable.

You might also like