Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
packing
communitycreator

How to pack and unpack tuples in Python

Sarah Tanveer

Tuples are immutable, ordered lists of Python objects.

Packing tuples

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

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.

Code

var1 = 2
var2 = 0.4
var3 = "Hello"
var4 = [1, 2, 3, 4]

# Packing tuple
tuple1 = (var1, var2, var3, var4)
print("Tuple: ", tuple1)

# Unpacking tuple
intObj, floatObj, strObj, listObj = tuple1
print("intObj: ", intObj)
print("floatObj: ", floatObj)
print("strObj: ", strObj)
print("listObj: ", listObj)

# Accessing different objects in tuple
# first object
firstObj = tuple1[0]
print("Object on index 0: ", firstObj)
thirdObj = tuple1[2]
print("Object on index 2: ", thirdObj)

Type of errors

1. TypeError

var1 = 2
var2 = 0.4
var3 = "Hello"
var4 = [1, 2, 3, 4]

# Packing tuple
tuple1 = (var1, var2, var3, var4)
print("Tuple: ", tuple1)

# trying to change the last object will throw a TypeError
print("TypeError is raised: ")
tuple1[3] = "C++"

2. ValueError

var1 = 2
var2 = 0.4
var3 = "Hello"
var4 = [1, 2, 3, 4]

# Packing tuple
tuple1 = (var1, var2, var3, var4)
print("Tuple: ", tuple1)

# trying to unpack when number of variables is not equal
# to the num of objects in the tuple
print("ValueError is raised: ")
intObj, floatObj, strObj = tuple1

RELATED TAGS

python
packing
communitycreator
RELATED COURSES

View all Courses

Keep Exploring