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.
>>> 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.
>>> a , *b, c = [1, 2, 3, 4, 5] >>> a 1 >>> b [2, 3, 4] >>> c 5 >>>
>>> l1 = [1, 2, 3, 4] >>> l2 = [5, 6, 7, 8] >>> l3 = [*l1, *l2] >>> l3 [1, 2, 3, 4, 5, 6, 7, 8] >>>
>>> dict1 = {1:'a', 2:'b'} >>> dict2 = {3:'c', 4:'d'} >>> dict3 = {**dict1, **dict2} >>> dict3 {1: 'a', 2: 'b', 3: 'c', 4: 'd'} >>>
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.
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.