T (22,33,44,55) T (0) 777 Print (T) Output: Typeerror: 'Tuple' Object Does Not Support Item Assignment
T (22,33,44,55) T (0) 777 Print (T) Output: Typeerror: 'Tuple' Object Does Not Support Item Assignment
Tuple:
Tuple is same as list data type, except Tuple is immutable. Tuple is represented by using
( ). If we change content inside the data type, then it is called as mutable data type, If we
cannot change the content inside a data type then it is called as immutable data type.
t=(22,33,44,55)
t[0]=777
print(t)
output:
TypeError: 'tuple' object does not support item assignment
t=(20)
print(type(t))
ouput:
D:\>python program1.py
<class 'int'>
Note: If we write one value inside parenthesis(without comma) then it will be treated as
integer data type
t=(20,)
print(type(t))
output:
D:\>python program1.py
<class 'tuple'>
t=()
print(type(t))
output:
D:\>python program1.py
<class 'tuple'>
t=10,20,30
print(type(t))
output:
Python 22 batch 7 pm Page 1
output:
D:\>python program1.py
<class 'tuple'>
example: t=(10,)
example: t=(10,20,30,40)
we can create other data types to tuple data type by using tuple().
l=[44,67,89,99]
t=tuple(l)
print(t)
t=tuple("apple")
print(t)
t=tuple(range(1,11))
print(t)
output:
D:\>python program1.py
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
t=(12,44,23,11)
print(t[1]) #44
print(t[-1]) #11
print(t[-4]) #12
output
D:\>python program1.py
44
11
12
t=(12,44,23,11)
print(t[2:6])
output:
(23,11)
Will list data type elements occupies more memory size or Tuple data type elements
occupies more size in memory?
l=[22,33,44,55]
t=(22,33,44,55)
program:
import sys
l=[22,33,44,55]
t=(22,33,44,55)
print(sys.getsizeof(l))
print(sys.getsizeof(t))
output
Python 22 batch 7 pm Page 3
D:\>python program1.py
88
72
List data type occupies more memory then tuple data type, because list is a mutable
data type where as tuple is a immutable data type. so extra memory is allocated for list
for placing new elements inside the list.
l=[22,33,44,55]
l[0]=9999999999999999999999999999999999999999999999999999999999999
print(l)
1.Concatenation Operator
2.Repetation Operator
If we want to combine two tuples then we should use concatenation Opearator. For
using concatenation Operator both variable must be of tuple data type only.
t1=(44,23)
t2=(21,31)
t3=t1+t2
print(t3)
output:
(44,23,21,31)
Example:
t1=(44,23)
t2=3
t3=t1+t2
print(t3)
output:
TypeError: can only concatenate tuple (not "int") to tuple
2.Repetation Operator:
Python 22 batch 7 pm Page 4
we can use repetation operator to repeat the elements inside the tuple
t1=(21,33)
t2=t1*3
print(t2)
output:
(21,33,21,33,21,33)
Program:
Given a list of numbers, write a program to create a list of tuples having first elements
as the number and second elements as the cube of the number
l=[1,2,3]
output:
[(1,1),(2,8),(3,27)]
[9,5,6]
output:
[(9,729),(5,125),(6,216)]