[what] More Data Operations In Python - Packing/Unpacking Statements



Python provides a special facility to assign content of collection data types into multiple variables and vice versa that is call packing/unpacking.

Packing = assigning multiple values to a single variable.

Unpacking = assigning  multiple values to multiple variables.

In short, assigning multiple values (as well as single value) to multiple variables is possible in Python.


print("\n====================\n")
# packing
print("Packing items")
packedVar = 10,20,30,40
print(type(packedVar))
print(packedVar)
print("\n====================\n")
# unpacking
print("Unpacking items")
a,b,c,d = packedVar
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(a,b,c,d)
print("\n====================\n")
# unpacking errors
print ("Unpacking errors")
try:
  p,q,r= [10,20,30,40]
except Exception as e:
  print(e)
print("\n====================\n")  
# solving unpacking errors through slicing
print ("Solving unpacking errors through slicing")
try:
  p,q,r= packedVar[0],packedVar[1:3],packedVar[3]
except Exception as e:
  print(e)
print(type(p)) 
print(p)
print(type(q)) 
print(q)
print(type(r)) 
print(r)
print ("Note: in Python 3, use of * for dynamic unpacking is also possible")
print ("Example: p, *q, r = packedVar")
print("\n====================\n")  
# assigning multiple values to multiple variables
length1,width1,height1 = 5,4,3
volume1=length1*width1*height1
print("volume = %d" % volume1)
print("\n====================\n")  
# assigning a single value to multiple variables
length2 = width2 = height2 = 5
volume2=length2*width2*height2
print("volume = %d" % volume2)
print("\n====================\n")


a carpet plot diagram consisting of four variables




Post a Comment

0 Comments