Tuesday, January 26, 2021

Tuple in python

Contents:

Introduction:

In python tuple is a immutable sequence that is used to store value of any type. Some of its feature are listed below:

  • Tuple are immutable i.e. The elements of the tuple cannot be changed in place.
  • The values in a tuple are enclosed in parentheses i.e. ( )

Creation of Tuple

Whenever the data of any type is enclosed in parentheses, then it becomes a tuple.Example:

In [1]:
()                    #Tuple with no members, empty tuple
(1,2,3)               #tuple of integer
(1,2.5,'hello')       #Heterogenous tuple i.e. tuple containing multiple data type
('a','b','d')         # tuple of string
Out[1]:
('a', 'b', 'd')

Empty Tuple:

In [3]:
tu=tuple()
print(tu)
()

Single element tuple:

In [4]:
tu=(1)
print(tu)
1

Creating tuple from existing sequences:

In [5]:
tu=tuple([12,13,14,15,16])
print(tu)
(12, 13, 14, 15, 16)
In [6]:
tu=tuple("Hello")
print(tu)
('H', 'e', 'l', 'l', 'o')
In [7]:
val=input("enter a value")
tu=tuple(val)
print(tu)
enter a value4356
('4', '3', '5', '6')

Accessing/Traversal of tuple:

In [1]:
#Accessing an individual element
vowels=('a','e','i','o','u')
vowels[2] 
Out[1]:
'i'
In [2]:
vowels=('a','e','i','o','u')
for i in vowels:
    print(i)
a
e
i
o
u

Operation on tuple:

Joining tuple: + operator can be used to join/Concatenate tuple

In [3]:
tp1=(1,2,3,4)
tp2=(5,6,7,8)
tp1+tp2
Out[3]:
(1, 2, 3, 4, 5, 6, 7, 8)

Replicating Tuple: * operator with an integer can be used to replicate tuple

In [4]:
tp1=(1,2,3,4)
tp1*3
Out[4]:
(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)

Slicing Tuple:  Tuple slicing is similar to List slicing

Syntax:
seq=T[start:stop:step]

In [10]:
#Slicing a tuple
tp1=(1,2,3,4,5,6,7)
tp1[2:5]
Out[10]:
(3, 4, 5)
In [11]:
#Striding a tuple
tp1=(1,2,3,4,5,6,7)
tp1[2:5:2]
Out[11]:
(3, 5)

Note:  

Creating a tuple from a set of values is called packing and its reverse i.e. creating individual values from a tuple's elements is called unpacking.
Syntax:
variable1,variable2,variable3,..= t

In [13]:
a,b,c=(10,12,13) #TUPLE UNPACKING
print(a)
print(b)
print(c)
10
12
13

Membership operation:

in and not in

can be used to check for membership in a tuple

In [17]:
tp1=(1) 
tp2=(1,2,3,4,5)
print(tp1 in tp2)
print(tp1 not in tp2)
True
False

Mean of the elements of a tuple:

In [18]:
tp=(10,20,30,40,50)
s=0
for i in tp:
    s=s+i
mean=s/len(tp)
print(mean)
30.0

Linear search on a tuple of numbers:

In [20]:
tp=(10,20,30,40,50)
f=int(input("Enter the element to search"))
if f in tp:
    print("The element is present")
else:
    print("The element is absent")
Enter the element to search11
The element is absent

Counting the frequency of elements in a tuple:

In [21]:
tp=(10,15,10,12,10,11,10)
count=0
elm=10
for i in tp:
    if elm==i:
        count+=1
print("The number of occurances of ",elm," is ",count)
The number of occurances of  10  is  4

Deleting element from Tuple:  del statement can be used to delete an entire tuple but individual element can not be deleted as tuple are immutable

In [26]:
tp=(10,15,10,12,10,11,10)
del tp
print(tp)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-26-11f091e461b0> in <module>
      1 tp=(10,15,10,12,10,11,10)
      2 del tp
----> 3 print(tp)

NameError: name 'tp' is not defined

Function/Methods on Tuple:

len():

In [28]:
tp=(10,15,10,12,10,11,10)
len(tp)
Out[28]:
7

max():

In [29]:
tp=(10,15,10,12,10,11,10)
max(tp)
Out[29]:
15

min():

In [30]:
tp=(10,15,10,12,10,11,10)
min(tp)
Out[30]:
10

tuple_name.count(item):  Returns the count of a members element/object in the tuple

In [33]:
tp=(10,15,10,12,10,11,10)
tp.count(10)
Out[33]:
4

tuple():  converts the sequence(list,string) into tuple

In [35]:
ls=[10,20,30,40,50]
tp=tuple(ls)
print(tp)
str="Computer"
tp2=tuple(str)
print(tp2)
(10, 20, 30, 40, 50)
('C', 'o', 'm', 'p', 'u', 't', 'e', 'r')

index

In [36]:
tp=(10,15,10,12,10,11,10)
tp.index(10)
Out[36]:
0

sorted():  

Sorted() method sorts a Sequence(List,Tuple,String) and always returns a list with the elements in a sorted manner, without modifying the original sequence.Reverse = True argument can be used to sort in Decreasing order

In [7]:
tp=(10,15,10,12,10,11,10)
sorted(tp, reverse=True)
Out[7]:
[15, 12, 11, 10, 10, 10, 10]

Excercise:

  1. Write a python program that creates a tuple storing first 9 terms of Fibonacci series.
  2. Given a tuple pairs=((2,5),(4,2),(9,8),(12,10)), count the number of pairs (a,b) such that both a and b are even
  3. Mean of Means: Given a nested tuple tup1=((1,2),(3,4.15,5.15),(7,8,12,15)). write a program that display the means of individual elements of tuple tup1 and then display the mean of these compound mean. That is for above tuple, it display as:
    Mean element 1: 1.5;
    Mean element 2: 4.1
    Mean element 3: 10.5
    Mean of means 5.366666
In [ ]:
 
Share: