tuple:
- It can be created by using parenthesis i.e ( ) or by using tuple function.
- tuple is a immutable object But the elements of the tuple can be mutable or immutable.
- tuple supports +ve and -ve indexes.
- Insertion order is preserved.
- Duplicate elements are allowed.
- Heterogeneous elements are allowed.
Example1:
x=tuple()
print(x)
print(type(x))
print(len(x))
Output:
( )
<class 'tuple'>
0
Example2:
y=(10,40,20,30,10,20,1.1,True,3+4j)
print(y)
print(type(y))
print(len(y))
Output:
(10, 40, 20, 30, 10, 20, 1.1, True, (3+4j))
<class 'tuple'>
9
Example3:
z=11,22,33
print(z)
print(type(z))
print(len(z))
Output:
(11, 22, 33)
<class 'tuple'>
3
Example4:
a=(10,20,30,40,50)
print(a)
print(a[2])
print(a[-2])
print(a[2:5])
print(a[5:2])
Output:
(10, 20, 30, 40, 50)
30
40
(30, 40, 50)
( )
Example5:
b=tuple('python')
print(b)
Output:
('p', 'y', 't', 'h', 'o', 'n')
Example6:
p=(100,200,300)
print(p)
c,d,e=p
print(c)
print(d)
print(e)
print(200 in p)
print(400 in p)
print(200 not in p)
print(400 not in p)
Output:
(100, 200, 300)
100
200
300
True
False
False
True
Example7: for loop
x=(10,20,30,40,50)
sum1=0
for i in x:
sum1=sum1+i
print(sum1)
Output:
150
Example8: while loop
y=(10,20,30,40,50)
sum2=0
i=0
while i<len(y):
sum2=sum2+y[i]
i=i+1
print(sum2)
Output:
150
Example9:
x=((11,22,33),(44,55,66),(77,88,99))
for i in x:
print(type(i))
for j in i:
print(j)
Output:
<class 'tuple'>
11
22
33
<class 'tuple'>
44
55
66
<class 'tuple'>
77
88
99
Example10:
x=((10,20,30),[40,50,60],(70,80,90))
print(x)
for p in x:
print(p,type(p))
for q in p:
print(q)
x[1][2]=555
print(x)
Output:
((10, 20, 30), [40, 50, 60], (70, 80, 90))
(10, 20, 30) <class 'tuple'>
10
20
30
[40, 50, 60] <class 'list'>
40
50
60
(70, 80, 90) <class 'tuple'>
70
80
90
((10, 20, 30), [40, 50, 555], (70, 80, 90))
Methods in tuple
Example:
x=(10,20,30,40,10,20,10)
print(x.count(10))
print(x.index(10))
print(x.index(10,3))
Output:
3
0
4
Note:
- Comprehension is not supported in immutable objects.
- If we try to apply the tuple comprehension we will not get the tuple object. But we will get the generator object.
Example:
x=(p for p in range(10))
print(x)
Output:
<generator object <genexpr> at 0x0000000003523EB8>
Differences between list and tuple:
list:
These are mutable objects .
Applying the iterations on the list objects takes longer time.
list cannot be used as a key for the dictionary even though list contains immutable elements.
list objects are not write protected.
If the frequent operations are insertion,updation and deletion recommended to go for list
tuple:
These are immutable objects.
Applying the iterations on the tuple objects takes less time.
tuple can be used as a key for the dictionary if the tuple contains mutable elements.
tuple objects are write protected.
If the frequent operations are retrieval of the elements then it then is recommended to use tuple.