Header Ads Widget

Responsive Advertisement

Packing and Unpacking of Tuples



Packing and Unpacking of Tuples:


Since Tuples are an ordered sequence of mixed data types and are immutable which means they cannot be modified in whole program once the item assignment is done.


In Python there is a feature to assign right hand side values into left hand side which is known as unpacking of tuples of values into a variable. We can extract those values into a single variable.


e.g.     x = ('Python' , 20, 'Program' )         #Packing of tuples.
              (language, no , Question ) = x      #Unpacking of tuples.

x = ('Python', 20, 'Program')  # Packing of tuples

(language, no, Question) = x # Unpacking of tuples

# Extracting values
print(language)
print(no)
print(Question)

# OUTPUT:
Python
20
Program

We have a special syntax to pass arguments(*args) for unpacking of tuples.

tup = ('TCS', 112 , 113, 114, 'Teacher')    # Packing of tuples

(Company, *Employee_id, Designation) = tup # Unpacking of tuples

print(Company) # prints TCS.
print(*Employee_id) #Except first and last element it will print all other elements.
print(Designation) # prints Teacher.
#OUTPUT:

TCS
112 113 114
Teacher

We can remove unwanted arguments also from tuples by using "*_'' operator.
e.g. 

tup = ("devpythonic", "Python","3.x.", "version","Data Structure:","tuples")

# UnPacking tuple variables into a group of arguments and skipping unwanted arguments

(blog , *_ , sub_topic , topic ) = tup

print(blog, "\t" , sub_topic ," ", topic)
# OUTPUT:
devpythogonic Data Structure: tuples

We can use this feature of unpacking tuples for slicing purposes also.
e.g. ,

tup = ('TCS', 112 , 113, 114, 'Teacher')    # Packing of tuples
(Company, *Employee_id, Designation) = tup # Unpacking of tuples
print(Employee_id[0])
print(Employee_id[1])
print(Employee_id[2])
print(*Employee_id[0:4])
#OUTPUT:
112
113
114
112 113 114

Thanks for reading ❤













Post a Comment

1 Comments