How to use asterisk (*) symbol in python
Published on Aug. 22, 2023, 12:16 p.m.
In Python, the asterisk (*) symbol can be used in several different ways depending on the context. Here are a few common use cases:
- Multiplication: The asterisk can be used as the multiplication operator to perform arithmetic multiplication between numbers or variables.
- Power: The asterisk can also be used to raise a number to a power, e.g.
2**3
would evaluate to 8. - String concatenation: When used with strings, the asterisk can replicate a string a given number of times. For example,
"hello" * 3
would evaluate to “hellohellohello”. - Argument unpacking: When used in a function call, the asterisk can unpack an iterable object (such as a list or tuple) and pass its contents as separate arguments to the function. For example,
my_function(*my_iterable)
would pass each element ofmy_iterable
as a separate argument tomy_function
. - Keyword argument unpacking: Similarly, a double asterisk (**) can be used to unpack a dictionary and pass its key-value pairs as separate keyword arguments to a function.
- Variadic function arguments: In function definitions, asterisk and double asterisk can be used to accept an arbitrary number of arguments. The single asterisk is used to capture positional arguments, while the double asterisk is used to capture keyword arguments.
These are just a few of the many ways that the asterisk symbol can be used in Python.