Unpacking a tuple in Python

Python Methods and Functions

Packing and Unpacking a Tuple : Python has a very powerful tuple assignment function that assigns the right side of values ​​to the left side. This is also called unpacking a tuple of values ​​into a variable. When packing, we put the values ​​into a new tuple, and when unpacking, we extract these values ​​into one variable.

Example 1

# Program for understanding
# packing and unpacking in Python

 
# these are PACKS value strings
# into variable a

a = ( " MNNIT Allahabad " , 5000 , "Engineering"

 
# these are UNPACKS value strings
Variable # a

(college, student, type_ofcollege) =

 
# print college name

print (college)

 
# print student #

print (student)

 
# college print type

print (type_ofcollege)

Output :

 MNNIT Allahabad 5000 Engineering 

NOTE. When unpacking a tuple, the number of variables on the left is must be equal to the number of values ​​in the given tuple a.

Python uses a special syntax for ne passing optional arguments (* args) to unpack tuples. This means that in python there can be many arguments instead of (* args). All values ​​will be assigned to each variable on the left side and all other values ​​will be assigned to * args. For a better understanding, consider the following code. 
Example 2

# Python code to learn
# unpack a python tuple using *

  
# the first and last will be assigned to x and z
# the rest will be assigned to you

x, * y, z = ( 10 , "Geeks" , "for" , "Geeks" , 50 )

 
# print details

print (x)

print (y)

print (z)

 
# the first and second will be assigned to x and y
# the rest will be assigned to z

x, y, * z = ( 10 , "Geeks" , "for" , "Geeks" , 50 )

print (x)  

print (y)

print (z)

Output:

 10 ['Geeks', 'for', 'Geeks'] 50 10 Geeks ['for', 'Geeks', 50] 

In Python tuples can be unpacked using a function, a tuple is passed to a function, and values ​​are unpacked in a function into a regular variable. Consider the following code for a better understanding. 
Example 3:

# Python code to learn
# unpack a Python tuple using the function

  
# the function takes normal arguments
# and multiply them

def result (x, y):

  return x * y

# function with normal variables

print (result ( 10 , 100 ))

  
# Tuple created

z = ( 10 , 100 )

 
# Tuple passed
# function unpacked them

 

print (result ( * z))

Output:

 1000 1000 




Get Solution for free from DataCamp guru