Try it here
Subscribe
Asterisk Operators: * & **

Python unpacking operator : * and **

python_unpacking_operator_:_*_and_**

The single and double asterisk unpacking operators were introduced in Python 2. In short, the unpacking operators are operators that unpack the values from iterable objects in Python. The single asterisk operator * can be used on any iterable that Python provides, while the double asterisk operator ** can only be used on dictionaries.

Define a list and print it.

>>> list1 = [1, 2, 3, 4]
>>> print(list1)
[1, 2, 3, 4]
>>> 

when print the list, list is printed, along with the corresponding brackets and commas.

Now, try to prepend the unpacking operator * to the name of your list:

>>> print(*list1)
1 2 3 4

Here, the * operator tells print() to unpack the list first.

In this case, the output is no longer the list itself, but rather the content of the list, here instead of a list, print() has taken three separate arguments as the input.

Unpacking with function arguments

>>> def get_sum(a, b, c):
    return a+ b+ c

>>> params = [1, 2, 3]
>>> get_sum(*params)
6
>>> 

Here, the params is unpacked first and passed as three arguments to function get_sum.

Unpacking into variables

>>> a , *b, c = [1, 2, 3, 4, 5]
>>> a
1
>>> b
[2, 3, 4]
>>> c
5
>>> 

Merge tow list using Unpacking operator

>>> l1 = [1, 2, 3, 4]
>>> l2 = [5, 6, 7, 8]
>>> l3 = [*l1, *l2]
>>> l3
[1, 2, 3, 4, 5, 6, 7, 8]
>>> 

Merge tow dictionaries using Unpacking operator

>>> dict1 = {1:'a', 2:'b'}
>>> dict2 = {3:'c', 4:'d'}
>>> dict3 = {**dict1, **dict2}
>>> dict3
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
>>> 

Unpack a string

the * operator works on any iterable object. It can also be used to unpack a string.

>>> s = 'deexams'
>>> print([*s])
['d', 'e', 'e', 'x', 'a', 'm', 's']
>>> 

The above example is same as this:

>>> *a, = 'deexams'
>>> a
['d', 'e', 'e', 'x', 'a', 'm', 's']
>>> 

The comma after the a makes it a tuple. When you use the unpacking operator with variable assignment, Python requires that your resulting variable is either a list or a tuple. With the trailing comma, you have actually defined a tuple with just one named variable a.

Writer profile pic

Karthik on Sep 20, 2020 at 09:09 am


This article is contributed by Karthik. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.



Post Comment

Comments( 0)

×

Forgot Password

Please enter your email address below and we will send you information to change your password.