analitics

Pages

Saturday, January 11, 2020

Python 3.7.5 : About asterisk operators in Python.

The asterisk known as the star operator is used in Python with more than one meaning attached to it.
Today I will show you some simple examples of how can be used.
Let's start with these issues.
You can merge two or more dictionaries by unpacking them in a new one:
>>> a = {'u': 1}
>>> b = {'v': 2}
>>> ab = {**a, **b, 'c':'d'}
>>> ab
{'u': 1, 'v': 2, 'c': 'd'}
Create multiple assignments:
>>> *x, y = 1, 2, 3, 4
>>> x
[1, 2, 3]
You can split into lists and generate sets:
>>> *a, = "Python"
>>> a
['P', 'y', 't', 'h', 'o', 'n']
>>> print(a)
['P', 'y', 't', 'h', 'o', 'n']
>>> *a,
('P', 'y', 't', 'h', 'o', 'n')
>>> zeros = (0,) * 8
>>> print(zeros)
(0, 0, 0, 0, 0, 0, 0, 0)
For numeric data types is used as multiplication operator:
>>> 2 * 3
6
You can use in mathematical function as an exponent:
>>> 3**2
9
You can create a sequences of strings using it like a repetition operator:
>>> t = 'Bye!'
>>> t * 4 
'Bye!Bye!Bye!Bye!'
>>> p = [0,1]
>>> p * 4 
[0, 1, 0, 1, 0, 1, 0, 1]
>>> r = (0,1)
>>> r * 4
(0, 1, 0, 1, 0, 1, 0, 1)
You can used into definition with arguments: *args and **kwargs:
def set_zero(*args):
    result = 0
The *args will give you all function parameters as a tuple.
The **kwargs will give you all keyword arguments except for those corresponding to a formal parameter as a dictionary.
See the PEP 3102 about Keyword-Only Arguments.