Asterisks meaning in Python

Posted by Afsal on 30-Sep-2022

Hi Pythonistas!

Today we will learn the different use of Asterisks(*) in Python. Let us understand one by one

For Multiplication

>>> a = 2
>>> a * 2
4
>>>

For find exponential

>>> a = 3
>>> a**2
9

As the variable positional argument

>>> def add(*args):
...     result = 0
...     for x in args:
...         result += x
...     return result
...
>>> add(3,6,7)
16
>>> add(3,6,7, 4, 4)
24
>>>

As the variable keyword argument

>>> def total_marks(**kwargs):
...     print(kwargs)
...
>>> total_marks(science=100, english=80, hindi=100)
{'science': 100, 'english': 80, 'hindi': 100}
>>> total_marks(science=100, english=80)
{'science': 100, 'english': 80}
>>>

To learn more about args and kwargs click here

For extended unpacking

Consider the case where we are not sure about the number of items in a list or tuple but we need the first and last item in the variable and the rest of the items in another variable. For this case, we can use extended unpacking

>>> a = [1, 2]
>>> b, *c, d = a
>>> b
1
>>> c
[]
>>> d
2
>>> a = [1, 2, 3]
>>> b, *c, d = a
>>> b
1
>>> c
[2]
>>> d
3
>>> a = list(range(10))
>>> b, *c, d = a
>>> b
0
>>> c
[1, 2, 3, 4, 5, 6, 7, 8]
>>> d
9
>>>

Hope you have learned something from this post. Please share your feedback with afsal@parseltongue.co.in