Member-only story
Unpacking Operators in Python
Using the * and ** unpacking operators in Python
Introduction
In this tutorial, we will learn how to use the asterisk (*) operator to unpack iterable objects, and two asterisks (**) to unpack dictionaries. In addition, we will discuss how we can pack several values into one variable using the same operator. And lastly, we will discuss what *args and **kwargs are and when they can be used.
* Operator
Let’s say we have a list:
num_list = [1,2,3,4,5]
And we define a function that takes in 5 arguments and returns their sum:
def num_sum(num1,num2,num3,num4,num5):
return num1 + num2 + num3 + num4 + num5
And we want to find the sum of all the elements in num_list. Well, we can accomplish this by passing in all the elements of num_list to the function num_sum. Since num_list has five elements in it, the num_sum function contains five parameters, one for each element in num_list.
One way to do this would be to pass the elements by using their index as follows:
num_sum(num_list[0], num_list[1], num_list[2], num_list[3], num_list[4])# 15