Introduction to Tuple


☞ It is a data structure.

☞ It is represented by ( ) parentheses.

☞ It is a sequence of python object i.e. integer, float, string, list etc.

Syntax :
variable_name = ( value1, value2, ………..valueN )

                     OR
 
variable_name = value1, value2, ………..valueN 

Creating an empty tuple :

Example :
T1 = ()
print(T1)

T2 = tuple()
print(T2)
Output
()
()

Creating a single element tuple : To do this, use comma after a value.

Example :
T3 = (36,)
print(T3)
Output
(36,)

Creating a tuple with homogeneous and heterogeneous elements :

Example :
T4 = (10, 20, 30, 40)  #homogeneous elements
print(T4)

T5 = 10, 20, 30, 40  
print(T5)

T6 = (10, "inspirewebsoft", 25.6, True, (10,20), [23,14], {"a":5, "b":6})      #heterogeneous elements
print(T6)
Output
(10, 20, 30, 40)
(10, 20, 30, 40)
(10, "inspirewebsoft", 25.6, True, (10,20), [23,14], {"a":5, "b":6})

Elements are addressed using their index value : Index starts with 0.

Example :
T4 = (10, 20, 30, 40)

It is immutable, but member objects may be mutable.

Example 1 :
T = (10, 20, 30, 40)
T[2] = 80 
print(T)
Output
T[2] = 80        #Error
TypeError: 'tuple' object does not support item assignment
Example 2 :
T = (10, 20, ["inspire", "wbe", "soft"], 40)
T[2] [1]= "web"       #No Error
print(T)
Output
(10, 20, ['inspire', 'web', 'soft'], 40)