Python Tuple

Tuple is exactly same as List except that it is immutable. i.e once we creates Tuple object,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.

We can preserve insertion order and we can differentiate duplicate objects by using index. Hence index will play very important role in Tuple also.

Tuple support both +ve and -ve index. +ve index means forward direction(from left to right) and -ve index means backward direction(from right to left)

We can represent Tuple elements within Parenthesis and with comma separators. Parenthesis are optional but recommended to use.

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

Output
(10, 20, 30, 40)

t=()
print(type(t)) # tuple

Note:
We have to take 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))

Output
10


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

Output
(10,)


Which of the following are valid tuples?
t=()
t=10,20,30,40
t=10
t=10,
t=(10)
t=(10,)
t=(10,20,30,40)

Tuple creation:

t=()

creation of empty tuple

t=(10,)
t=10,

creation of single valued tuple ,parenthesis are optional, should ends with comma

t=10,20,30

t=(10,20,30)

creation of multi values tuples & parenthesis are optional

By using tuple() function:

list=[10,20,30]
t=tuple(list)
print(t)
t=tuple(range(10,20,2))
print(t)

Accessing elements of tuple:

We can access either by index or by slice operator

By using index:

t=(10,20,30,40,50,60)
print(t[0]) #10
print(t[-1]) #60
print(t[100]) IndexError: tuple index out of range

By using slice operator:

t=(10,20,30,40,50,60)
print(t[2:5])
print(t[2:100])
print(t[::2])

Output
(30, 40, 50)
(30, 40, 50, 60)
(10, 30, 50)

Tuple vs immutability:

  • Once we creates tuple,we cannot change its content.
  • Hence tuple objects are immutable.

Ex:
t=(10,20,30,40)
t[1]=70 TypeError: ‘tuple’ object does not support item assignment

Mathematical operators for tuple:

We can apply + and * operators for tuple

Concatenation Operator(+):

t1=(10,20,30)
t2=(40,50,60)
t3=t1+t2
print(t3) # (10,20,30,40,50,60)

Multiplication operator or repetition operator(*)

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

Important functions of Tuple:

len()

To return number of elements present in the tuple

Ex:
t=(10,20,30,40)
print(len(t)) #4

count()

To return number of occurrences of given element in the tuple

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

index()

  • returns index of first occurrence of the given element.
  • If the specified 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 elements based on default natural sorting order

t=(40,10,30,20)
t1=sorted(t)
print(t1)
print(t)

Output
[10, 20, 30, 40]
(40, 10, 30, 20)

We can sort according to reverse of default natural sorting order as follows

t1=sorted(t,reverse=True)
print(t1) [40, 30, 20, 10]

min() and max() functions:


These functions return min and max values according to default natural sorting order.

Ex:
t=(40,10,30,20)
print(min(t)) #10
print(max(t)) #40

cmp():

  • It compares the elements of both tuples.
  • If both tuples are equal then returns 0
  • If the first tuple is less than second tuple then it returns -1
  • If the first tuple is greater than second tuple then it returns +1

Ex:
t1=(10,20,30)
t2=(40,50,60)
t3=(10,20,30)
print(cmp(t1,t2)) # -1
print(cmp(t1,t3)) # 0
print(cmp(t2,t3)) # +1

Note:
cmp() function is available only in Python2 but not in Python 3

Tuple Packing and Unpacking:

We can create a tuple by packing a group of variables.

Ex:
a=10
b=20
c=30
d=40
t=a,b,c,d
print(t) #(10, 20, 30, 40)

Here a,b,c,d are packed into a tuple t. This is nothing but tuple packing.

  • Tuple unpacking is the reverse process of tuple packing
  • We can unpack a tuple and assign its values to different variables

Ex:
t=(10,20,30,40)
a,b,c,d=t
print(“a=”,a,”b=”,b,”c=”,c,”d=”,d)

Output
a= 10 b= 20 c= 30 d= 40

Note:
At the time of tuple unpacking the number of variables and number of valuesshould be same.Otherwise we will get ValueError.

Ex:
t=(10,20,30,40)
a,b,c=t #ValueError: too many values to unpack (expected 3)

Tuple Comprehension:

Tuple Comprehension is not supported by Python.

t= ( x**2 for x in range(1,6))

Here we are not getting tuple object and we are getting generator object.

t= ( x**2 for x in range(1,6))
print(type(t))
for x in t:
print(x)

Output
D:\Python_classes>py test.py
1
4
9
16
25

Write a program to take a tuple of numbers from the keyboard and print its sum and average?

t=eval(input(“Enter Tuple of Numbers:”))
l=len(t)
sum=0
for x in t:
sum=sum+x
print(“The Sum=”,sum)
print(“The Average=”,sum/l)

D:\Python_classes>py test.py
Enter Tuple of Numbers:(10,20,30,40)
The Sum= 100
The Average= 25.0

D:\Python_classes>py test.py
Enter Tuple of Numbers:(100,200,300)
The Sum= 600
The Average= 200.0

Follow Us On