You are currently viewing Understanding the Different Uses of the Asterisk(*) in Python

Understanding the Different Uses of the Asterisk(*) in Python

You must have seen the asterisk or star symbol inside the parameterized function or used it to perform mathematical or other high-level operations.

We’ll look at the different ways the asterisk(*) is used in Python in this article.

Asterisks(*) are used in the following situations:

  • Exponentiation and multiplication
  • Unpacking/Packing
  • Repetition
  • Formatting Strings
  • Tuple and Set Unpacking
  • Asterisk to Bound Function’s Parameters to the keyword-only Argument

Let’s begin by breaking down the use of asterisks in the above cases one by one.

Multiplication

Python has arithmetic operators, one of which is an asterisk(*), which is commonly used to perform multiplication operations.

In the above code, we performed a simple arithmetic operation by multiplying 9 and 7 using the asterisk(*) as the multiplication operator.

And we can do this also.

The above code defines the function multiply, which takes two parameters a and b, and returns the product of a and b multiplied.

We multiplied the "Geek" and 5 arguments and printed the result. As we can see in the output, the argument "Geek" was multiplied by 5.

Exponentiation

Similarly, we can use the asterisk to perform an exponentiation operation, but to get the exponential value of an integer, we must use a double asterisk(**).

We obtained 256 as the result of evaluating 4 raised to power 4(4**4). The double asterisk(**) is also known as the power operator.

Packing and Unpacking

Before we begin, we must understand that there are two types of arguments: positional arguments and keyword arguments.

Positional arguments are passed to the function based on their position, whereas keyword arguments are passed to the function based on their parameter name.

Consider the following example of positional and keyword arguments.

The function friends in the above code take two positional arguments, f1 and f2, and two keyword arguments, f3 and f4, with a default value of None.

In the first case, we used two positional arguments "Rishu" and "Yashwant" and two keyword arguments f3="Abhishek" and f4="Yogesh" to call the function.

You can see how "Rishu" and "Yashwant" were passed into the position of f1 and f2, respectively, and "Abhishek" and "Yogesh" were passed with the parameter names f3 and f4. However, we cannot change the position, as we did in the second case by passing the keyword argument before the positional argument; doing so will result in a SyntaxError.

If we try to pass an arbitrary number of arguments inside the function friends, we will get an error. As a result, we need a way to pass variadic arguments within the function.

We can use *args and **kwargs to pass variadic arguments in situations where we need to.

Argument Packing

Passing variadic positional arguments

The function friends takes *args, indicating that the function accepts a variable number of positional arguments. We passed an arbitrary number of positional arguments, which were saved in the tuple called args.

Passing variadic keyword arguments

This time function accepts **kwargs, indicating that it accepts an arbitrary number of keyword arguments. We passed an arbitrary number of keyword arguments, which were saved in the dictionary called kwargs.

As a result, we can conclude that the asterisks with args and kwargs were used to pack the arguments.

Unpacking

We have used single and double asterisks as packing operators with args and kwargs, respectively, and we can also use them for unpacking.

The iterables are unpacked with a single asterisk(*), while the dictionaries are unpacked with a double asterisk(**).

We have a list of names and a function greet that accepts a variable number of positional arguments and iterates through them to print some information.

You’ll notice that we passed names_lst as *names_lst because this will unpack the items in the names_lst list.

If we had passed the names_lst to the function, we would have gotten the following result.

Similarly, we can unpack the dictionaries by using a double asterisk(**). Let us illustrate with an example.

The function occupation accepts **roles, which means we can pass an arbitrary number of keyword arguments when calling the function, and it then iterates through the key and value and prints them.

We called the function and passed the dictionary occ_dict prefixed with a double asterisk(**). This will unpack the dictionary’s keys and values, producing the output shown below.

Alternatively, we can pass the keyword arguments in the function call as shown below.

Repetition Of List And String

We can use an asterisk as a repetition operator, repeating the string or list for a specific number (similar to multiplying them). Let’s understand with an example.

In the above code, we are essentially multiplying or repeating whatever you want to call it. The output will be the string and list being repeated three times.

Asterisk In String Formatting

You must have used different methods to format the strings in Python. We can use the asterisk in string formatting to unpack the tuples/lists values.

We’ll use the .format string formatting method.

In the above code, we are just unpacking the list and tuple values using the single asterisk(*) passed within the .format string formatting.

This can only be used with the .format string formatting method, and the goal here is simply to demonstrate how we can use an asterisk while formatting strings.

Asterisks are not permitted to be used in other string formatting methods.

Tuple/Set Unpacking

We learned earlier in this article how to use * asterisks to unpack the iterable and ** asterisks to unpack the dictionary. In this section, we’ll use the asterisk to unpack the values contained within the tuple/set.

The set {'One', 'piece', 'is', 'real'} is unpacked into One piece is real in the preceding example.

Here’s an example of how to unpack a tuple.

The output shows that the tuple unpacks into x=Oney=['piece', 'is'], and z=real.

Asterisk to Bound Function’s Parameters to the keyword-only Argument

You might have seen a bare asterisk (*) in a function’s parameter list. Why bare asterisk is used and what it does?

In short, a bare asterisk (*) is used to control how to pass a value as an argument.

Here’s an example to show when a function has a bare asterisk in the parameter list, what does that imply?

The function func() takes three arguments: x, y, and z but it also has an asterisk (*) between the x, y and z parameters.

This means that the parameter on the right side of the asterisk is a keyword-only argument and the parameters on the left side can be passed as either positional or keyword argument.

But the parameter z is now obliged to keyword argument and if you pass it as a positional argument, the program will throw an error.

If you run the code, you’ll get the following error.

It says that the function func takes only two positional arguments but three positional arguments were supplied.

But if you pass z=4 in the function just like in the val_2 in the above code, the program will not throw any error.

Others

Another application of the asterisk could be in importing all of the classes and functions from the modules.

We were able to use the time and strftime functions from the time module because of the asterisk, which helps in the import of all functions and classes from the module.

Note: This is not a good practice at all, importing all the classes and functions from the module at a time can use up resources unnecessarily.

Conclusion

This article explains the use of asterisks in Python. We can use it as a multiplication operator or to pack and unpack arguments.

Let’s recall what we’ve learned:

  • Using asterisk for exponentiation and multiplication
  • Argument packing/unpacking
  • Using as a repetition operator
  • Using asterisk in the string formatting
  • Unpacking the tuple and set values
  • Asterisk to bound function’s parameters to the keyword-only argument

🏆Other articles you might be interested in if you liked this one

The concept of constructors and initializers in Python.

An improved and modern way of string formatting.

Public, Protected, and Private access modifiers in Python.

What are inheritance and different types of inheritance in Python?

What do they do – __init__ and __call__ methods?

How to implement __getitem__, __setitem__, and __delitem__ in Python class?

Displaying images on the frontend using FastAPI.


That’s all for now

Keep Coding✌✌