5 usages of an asterisk (*) in Python
5 usages of an asterisk (*) in Python
Star and Python
A star can be used in many scenarios in Python. Let’s start.
1. Star as a multiplication operator
>>> 5 * 6
30
>>> * 2
>>> * 2
2. Stars as exponential operator
>>> 2 ** 3
8
3. Star in arguments
>>> :
...
... return f
...
>>>
1
2
3
is: 6
Here the star helps to unpack iterables; called as unpacking operator.
4. Stars in keyword arguments
>>> :
... return f
...
>>>
is: 6
Double stars can be used to unpack a dictionary
5. Stars to update two dictionaries
Merging two dictionaries can be done in many ways.
>>> =
>>> =
>>> =
>>> = | # Union operator introduced recently
>>>
>>> # in place update
# as `y` value getting updated in `x`, `a` value getting overwritten from 1 to 10.
>>>
>>> =
>>>
# same key in two dictionaries will throw error
>>> =
:
1, in <>
, :
Further reading
- Do you know all the usage of the Underscore in Python?
- Cool Python tricks you are not using, but you should
- https://blog.soumendrak.com/cache-heavy-computation-functions-with-a-timeout-value
- In Python, do you know double for loops with conditions in a list-comprehension?
- Optimize your Python code
Photo by Michael Kilcoyne on Unsplash