hjdzlagis
December 12, 2024
Tuples
[1]: first_tuple=(12,'praveen',3.14,(3,4),'kumar',True)
first_tuple
[1]: (12, 'praveen', 3.14, (3, 4), 'kumar', True)
[3]: first_tuple[1],first_tuple[-5]
[3]: ('praveen', 'praveen')
[4]: first_tuple[-2],first_tuple[2]
[4]: ('kumar', 3.14)
[5]: first_tuple[1]='ajay'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-62048027a611> in <cell line: 1>()
----> 1 first_tuple[1]='ajay'
TypeError: 'tuple' object does not support item assignment
[6]: first_tuple
[6]: (12, 'praveen', 3.14, (3, 4), 'kumar', True)
[7]: first_tuple[1:3]
[7]: ('praveen', 3.14)
[9]: first_tuple[2:-2]
[9]: (3.14, (3, 4))
[10]: first_tuple[-4:-2]
1
[10]: (3.14, (3, 4))
[11]: first_tuple[1:4]
[11]: ('praveen', 3.14, (3, 4))
[12]: first_tuple[1:-1]
[12]: ('praveen', 3.14, (3, 4), 'kumar')
Tuples 1. immutable 2. read only lists 3. heterogenous data structures like lists 4. a list inside
a tuple can be mutated 5. because of the immutable property of the tuples, they occupy smaller
memory space than lists 6. lists are in [], tuple in ()
[13]: second_tuple=(2,3,5.67,8.90,'a',"hello",[23,45,"welcome",'hi'],(2,3,4))
second_tuple
[13]: (2, 3, 5.67, 8.9, 'a', 'hello', [23, 45, 'welcome', 'hi'], (2, 3, 4))
[14]: second_tuple[-2],second_tuple[2]
[14]: ([23, 45, 'welcome', 'hi'], 5.67)
[15]: second_tuple[::-2]
[15]: ((2, 3, 4), 'hello', 8.9, 3)
[16]: second_tuple[::2]
[16]: (2, 5.67, 'a', [23, 45, 'welcome', 'hi'])
[17]: second_tuple
[17]: (2, 3, 5.67, 8.9, 'a', 'hello', [23, 45, 'welcome', 'hi'], (2, 3, 4))
[18]: second_tuple[6].extend([5,6])
[19]: second_tuple
[19]: (2, 3, 5.67, 8.9, 'a', 'hello', [23, 45, 'welcome', 'hi', 5, 6], (2, 3, 4))
[20]: second_tuple[-2].extend(['list','extension'])
[21]: second_tuple
[21]: (2,
3,
5.67,
2
8.9,
'a',
'hello',
[23, 45, 'welcome', 'hi', 5, 6, 'list', 'extension'],
(2, 3, 4))
[23]: age=(30,45,67,23,21,70)
age
[23]: (30, 45, 67, 23, 21, 70)
[24]: random=list(age)
random
[24]: [30, 45, 67, 23, 21, 70]
[25]: random[2]
[25]: 67
[26]: random[2]=90
[27]: random
[27]: [30, 45, 90, 23, 21, 70]
[28]: age1=tuple(random)
age1
[28]: (30, 45, 90, 23, 21, 70)
[29]: age1.index(21)
[29]: 4
[30]: age1.count(90)
[30]: 1
[31]: age2=(12,34,56,78,12,35,34,12)
age2
[31]: (12, 34, 56, 78, 12, 35, 34, 12)
[33]: age2.count(12),age2.count(34)
[33]: (3, 2)