Python Unpacking variables

In python variables can be passed using unnamed parameters, can pass any number of variables without defining the number of the variables. In python, we can pass the keywords and the arguments as the variables and unpack the variables before assigning them. Variables can be assigned as tuples or dictionaries. Sample code is available in the Git

Assignment types

*args – pass the values of the variables. Python reads these arguments in the form of the tuple

**kwargs – pass the keyword arguments. Python reads these arguments in the form of the dictionary.

Using args and the keyword arguments makes the code more robust, easy to understand, debug. Name of the assignment variables can be anything not mandatory to use args or kwargs. Need to remember single * represents the variables arguments in the form and Double ** represents the keyword arguments.

 

Sample code

*args

Tuple, list or dictionary can be passed as the input arguments but python will always read these as a tuple. Once the variables read by the python can be used as the requirement as the code

#Reading the tuples

In the above example, * is not passed with the args in the function it will consider the input variable as “named parameter”. If we pass more than one value to the variable it will throw an error:

def read_tuple(args):
    print(‘args in tuple’, args)
#read_tuple(1)                # args in tuple 1
read_tuple(1,2,3)            # TypeError: read_tuple() takes 1 positional argument but 3 were given
# Use * with args to avoid the limitation of number of variables
def read_tuple(*args):
    print(‘args in tuple’, args)
    for var in args:
        print(var)

 

read_tuple(1,2,3)              # args in tuple (1, 2, 3)
read_tuple((1,2,3))           # args in tuple ((1, 2, 3),) return tuple of tupzle

#Reading the list

Python *args will consider the list as a tuple and need to process further to treat it as list

# Reading variables from list
def read_list(*args):
    print(‘args in list’, args)
    for var in args:
        for list_var in var:
            print(‘List var : ‘,list_var)
read_list([1,2,3])
# Output
args in list ([1, 2, 3],)
List var : 1
List var : 2
List var : 3

#Reading the dictionary

Python *args will consider the list as a tuple and need to process further to treat it as a list.

# Read only keys from dictionary
def read_dict(*args):
    print(‘args in list’, args)
    for key in args:
        print(‘key is : ‘,key)
read_dict(*{“x” : 1, “y” : 2})
# Output
args in dict (‘x’, ‘y’)
key is : x
key is : y

 

**kwargs

**kwargs are used to pass the keywords arguments to the Python. Keyword arguments are used to pass the key and values to

def func_1(**kwargs):
    for key, value in kwargs.items():
        print(‘key is {}, val is {}’.format(key, value))
        print(‘key using string formatting %s, value is %s’ %(key, value))
func_1(id = 1, country = ‘IN’)
# Output
key is id, val is 1
key using string formatting id, value is 1

*args and **kwargs

*args and **kwargs can be passed in same functions, for the **kwargs we need to pass the keyword name and value

def func_name(*args, **kwargs):
    print(‘args : ‘,args)
    print(‘kwargs : ‘, kwargs)
func_name(10, 20, 30, name = ‘Hadoop Tech’)
# Output
args : (10, 20, 30)
kwargs : {‘name’: ‘Hadoop Tech’}

Kindly share your feedback and questions and subscribe Hadoop Tech and our facebook page(Hadoop Tech) for more articles.

Leave a comment