Monday, 23 January 2017

TUPLE IN PYTHON

Tuple is used to represent group of elements into a single entity. Tuple objects are immutable objects i.e., once if you create tuple object with some element, later we cannot modify the elements of that object. Insertion order is preserved. Duplicate elements are allowed. Every element in the tuple object is represented with index. Tuple supports both forward and backward indexes.

Example –
a=()
print a
print type(a)
b=tuple()
print b
print type(b)
c=(1,2,3)
print c
print type(c)
d=(1,'hello',3.4)
print d
print type(d)
e=('mouse',[8,4,6],[1,2,3])
print e
print type(e)
f=3,4.6,'dog'
x,y,z=f
print x
print type(x)
print y
print type(y)
print z
print type(z)
 
Output –
()
<type 'tuple'>
()
<type 'tuple'>
(1, 2, 3)
<type 'tuple'>
(1, 'hello', 3.4)
<type 'tuple'>
('mouse', [8, 4, 6], [1, 2, 3])
<type 'tuple'>
3
<type 'int'>
4.6
<type 'float'>
dog
<type 'str'>


Example –
x=tuple('rakeshkumar')
print x
print len(x)
print x[5]
print x[-3]
y=x[2:7]
print y
print type(y)
print x[-7:-2]
del x[-2]
Output –
Traceback (most recent call last):
('r', 'a', 'k', 'e', 's', 'h', 'k', 'u', 'm', 'a', 'r')
  File "C:/Users/om/PycharmProjects/Pythonn/if3.py", line 10, in <module>
11
    del x[-2]
h
TypeError: 'tuple' object doesn't support item deletion
m
('k', 'e', 's', 'h', 'k')
<type 'tuple'>
('s', 'h', 'k', 'u', 'm')


Example –
x=(10,2.,30,10,40,50,10)
print x
for p in x:
    print p
y=(1.1,True,10,'rakesh')
print y
for q in y:
    print q

Output –
(10, 2.0, 30, 10, 40, 50, 10)
10
2.0
30
10
40
50
10
(1.1, True, 10, 'rakesh')
1.1
True
10
rakesh


Example –
x=([10,20,30],(40,50,60),'rakesh')
print x
for p in x:
    print p, type(p), len(p)
    for q in p:
        print q
 
Output –
([10, 20, 30], (40, 50, 60), 'rakesh')
[10, 20, 30] <type 'list'> 3
10
20
30
(40, 50, 60) <type 'tuple'> 3
40
50
60
rakesh <type 'str'> 6
r
a
k
e
s
h
 
 
Example –
x=(10,20,30,40,50,20,10,10)
print x
a=x.count(10)
print a
b=x.index(30)
print b
print 100 in x
 
Output –
(10, 20, 30, 40, 50, 20, 10, 10)
3
2
False
 
 
Example –
x=(10,20,30)
print x
print id(x)
y=(10,40,30)
print y
print id(y)
z=x+y
print z
print id(z)
a=(10,20,30)
print a
print id(a)
b=('rakesh','kumar')*3
print b
print x==a
print x is a
Output –
(10, 20, 30)
18988688
(10, 40, 30)
19535352
(10, 20, 30, 10, 40, 30)
47904280
(10, 20, 30)
47908104
('rakesh', 'kumar', 'rakesh', 'kumar', 'rakesh', 'kumar')
True
False
 
Note – Tuple comprehension is not supported in python, if we use it 
internally creates generator object
 
Example –
s=(x**2 for x in range(10))
print s
print type(s)
for p in s:
    print p
Output –
<generator object <genexpr> at 0x029C3288>
<type 'generator'>
0
1
4
9
16
25
36
49
64
81

No comments:

Post a Comment