Tuples are immutable, ordered lists of Python objects.
Packing tuples assigns multiple Python objects to a tuple.
tuple1 = (obj1, obj2, ..., objN)
Each object in tuples has an index and can be accessed using its index. Once an object has been assigned to a tuple, it cannot be changed, i.e., it is immutable.
Unpacking tuples assigns the objects in a tuple to multiple variables.
(obj1, obj2, ..., objN) = tuple1
During unpacking, the number of variables must be equal to the number of objects in the tuples. If this is not the case, a ValueError
is raised.
var1 = 2var2 = 0.4var3 = "Hello"var4 = [1, 2, 3, 4]# Packing tupletuple1 = (var1, var2, var3, var4)print("Tuple: ", tuple1)# Unpacking tupleintObj, floatObj, strObj, listObj = tuple1print("intObj: ", intObj)print("floatObj: ", floatObj)print("strObj: ", strObj)print("listObj: ", listObj)# Accessing different objects in tuple# first objectfirstObj = tuple1[0]print("Object on index 0: ", firstObj)thirdObj = tuple1[2]print("Object on index 2: ", thirdObj)
TypeError
var1 = 2var2 = 0.4var3 = "Hello"var4 = [1, 2, 3, 4]# Packing tupletuple1 = (var1, var2, var3, var4)print("Tuple: ", tuple1)# trying to change the last object will throw a TypeErrorprint("TypeError is raised: ")tuple1[3] = "C++"
ValueError
var1 = 2var2 = 0.4var3 = "Hello"var4 = [1, 2, 3, 4]# Packing tupletuple1 = (var1, var2, var3, var4)print("Tuple: ", tuple1)# trying to unpack when number of variables is not equal# to the num of objects in the tupleprint("ValueError is raised: ")intObj, floatObj, strObj = tuple1