Tuesday, June 30, 2020

Tuple Practice Python


tuple
In [1]:
()
Out[1]:
()
In [2]:
('a','b','abc',1,2,3)
Out[2]:
('a', 'b', 'abc', 1, 2, 3)
In [ ]:
t=()
p=tuple()
In [1]:
#tuple with single integer
p=3,
p
Out[1]:
(3,)
In [2]:
#not a tuple
q=(1)
q
Out[2]:
(1,)
In [3]:
#tuple with multi line 
tup=(1,2,2,4,
    6,7,7)
tup
Out[3]:
(1, 2, 2, 4, 6, 7, 7)
In [7]:
#nested tuple
tu=(1,2,(3,4))
tu
Out[7]:
(1, 2, (3, 4))
In [8]:
#string to tuple
s=tuple('hello')
s
Out[8]:
('h', 'e', 'l', 'l', 'o')
In [8]:
#list to tuple
li=[1,2,23,[4,5],5]
li[3]=tuple(li[3])
li=tuple(li)
li
Out[8]:
(1, 2, 23, (4, 5), 5)
In [10]:
#input to tuple conversion
tp=tuple(input('enter tuple element'))
tp
enter tuple element1234,[4,5]
Out[10]:
('1', '2', '3', '4', ',', '[', '4', ',', '5', ']')
In [5]:
#tuple creation using eval,enter contained in paranthesis
t1=eval(input('enter tuple member'))
type(t1)
enter tuple member'string'
Out[5]:
str
In [7]:
#slicing in tuple ,same as list
t1=('a','b',3,4,[6,7])
print(t1[0:])
print(t1[:-1])
('a', 'b', 3, 4, [6, 7])
('a', 'b', 3, 4)
In [8]:
#length function in tuple
len(t1)
Out[8]:
5
In [3]:
t1=(1,2,3)
t1[0]
Out[3]:
1
In [4]:
tpl=(10,12,14,20,22,24,30,32)
tpl[0:10:2]
Out[4]:
(10, 14, 22, 30)
In [5]:
tpl[1:4]*3
Out[5]:
(12, 14, 20, 12, 14, 20, 12, 14, 20)
In [6]:
tpl[2:5]+(3,4)
Out[6]:
(14, 20, 22, 3, 4)
In [14]:
#packing and unpacking tuple
t=(1,2,'a','b')
a,b=t[0:2]
print(a,b)
1 2
In [12]:
#deletion of individual element not possible in tuple
del t[1]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-ea171c76d51e> in <module>
      1 #deletion of individual element not possible in tuple
----> 2 del t[1]

TypeError: 'tuple' object doesn't support item deletion
In [15]:
#max() function intuple
t=(1,2,3,4)
print(max(t))
print(t.count(1))
4
1
In [16]:
t=(1,2,3,2,4)
t.index(2)
Out[16]:
1
In [3]:
t.count(6)
Out[3]:
0
In [4]:
t.count(2)
Out[4]:
1
In [5]:
tuple()
Out[5]:
()
In [6]:
#list to tuple
t=tuple([1,2,3])
t
Out[6]:
(1, 2, 3)
In [ ]:
t=(1,2,2,3)
tc=()
for a in len(t):
      tc+=(t.count(t[a]),)
print(tc)
In [ ]:
#string to tuple
ts=tuple('abc')
ts
In [9]:
t2=tuple({1:'1',2:'2'})
t2
Out[9]:
(1, 2)
In [12]:
#tuple tolist 
t3=(1,2,3)
l3=list(t3)
l3
Out[12]:
[1, 2, 3]
In [13]:
l3[1]=9
t3=tuple(l3)
t3
Out[13]:
(1, 9, 3)
In [3]:
t1='a','b'
t2=('a','b')
print(t1)
print(t2)
Out[3]:
('a', 'b')
In [ ]:
#tuple creation using eval,enter contained in paranthesis
t1=eval(input('enter tuple member'))
In [ ]:
t=(1,2,2,3)
tc=()
for a in len(t):
      tc+=(t.count(t[a]),)
print(tc)
In [ ]:
 

No comments:

Post a Comment