What Asterisk (*) Can Do In Python

sachingeek

Sachin

Posted on March 15, 2024

What Asterisk (*) Can Do 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

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.

# Multiplication using asterisk(*)
multiply = 9 * 7
print(multiply)

---------
63
Enter fullscreen mode Exit fullscreen mode

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.

def multiply(a, b):
    return a * b

product = multiply("Geek", 5)
print(product)

----------
GeekGeekGeekGeekGeek
Enter fullscreen mode Exit fullscreen mode

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(**).

# Exponentiation using asterisk(*)
expo = 4 ** 4
print(expo)

----------
256
Enter fullscreen mode Exit fullscreen mode

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.

# Positional and Keyword arguments
def friends(f1, f2, f3=None, f4=None):
    return f1, f2, f3, f4

# Passing two positional and two keyword argument
names = friends("Rishu", "Yashwant", f3="Abhishek", f4="Yogesh")
print(names)

# Passing keyword argument before the possitional argument
names1 = friends("Rishu", f4="Yogesh", "Yashwant")
print(names1)
Enter fullscreen mode Exit fullscreen mode

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.

Understanding args and kwargs in Python functions

Argument Packing

Passing variadic positional arguments

# Use of *args
def friends(*args):
    return args

# Passing variadic positional arguments
names = friends("Rishu", "Yashwant", "Abhishek", "Yogesh")
print(names)

----------
('Rishu', 'Yashwant', 'Abhishek', 'Yogesh')
Enter fullscreen mode Exit fullscreen mode

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

# Use of **kwargs
def friends(**kwargs):
    return kwargs

# Passing variadic keyword arguments
names = friends(f1="Rishu", f2="Yashwant", f3="Abhishek")
print(names)
Enter fullscreen mode Exit fullscreen mode

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(**).

# List of names
names_lst = ["Sachin", "Rishu", "Yashwant", "Abhishek"]

def greet(*names):
    for name in names:
        print(f'Welcome to GeekPython, {name}.')

message = greet(*names_lst)
Enter fullscreen mode Exit fullscreen mode

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.

Welcome to GeekPython, Sachin.
Welcome to GeekPython, Rishu.
Welcome to GeekPython, Yashwant.
Welcome to GeekPython, Abhishek.
Enter fullscreen mode Exit fullscreen mode

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

message = greet(names_lst)

----------
Welcome to GeekPython, ['Sachin', 'Rishu', 'Yashwant', 'Abhishek'].
Enter fullscreen mode Exit fullscreen mode

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

# Dictionary with name and roles
occ_dict = {
    "Sachin": "Python dev", 
    "Rishu": "C++ dev", 
    "Yashwant": "C++ dev", 
    "Abhishek": "PHP dev"
}

def occupation(**roles):
    for key, value in roles.items():
        print(f"{key} is a {value}.")

occupation(**occ_dict)
Enter fullscreen mode Exit fullscreen mode

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.

Sachin is a Python dev.
Rishu is a C++ dev.
Yashwant is a C++ dev.
Abhishek is a PHP dev.
Enter fullscreen mode Exit fullscreen mode

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

occupation(Sachin="Python dev", Rishu="C++ dev")

----------
Sachin is a Python dev.
Rishu is a C++ dev.
Enter fullscreen mode Exit fullscreen mode

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.

# Using asterisk as a repetition operator
data = "GeekPython" * 3
print(data)

print("-" * 20)

lst_data = ["Geek", "Python"] * 3
print(lst_data)
Enter fullscreen mode Exit fullscreen mode

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.

GeekPythonGeekPythonGeekPython
--------------------
['Geek', 'Python', 'Geek', 'Python', 'Geek', 'Python']
Enter fullscreen mode Exit fullscreen mode

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.

# Using asterisk in string formatting

# Unpacking list
data = "{} {} {}.".format(*["Welcome", "to", "GeekPython"])
print(data)

# Unpacking tuple
val = "{} {} {}.".format(*(1, 2, 3))
print(val)
Enter fullscreen mode Exit fullscreen mode

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

Welcome to GeekPython.
1 2 3.
Enter fullscreen mode Exit fullscreen mode

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.

x = {'One', 'piece', 'is', 'real'}
print(type(x))
print(*x)

----------
<class 'set'>
One real is piece
Enter fullscreen mode Exit fullscreen mode

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.

x, *y, z = ('One', 'piece', 'is', 'real')
print(x)
print(y)
print(z)

----------
One
['piece', 'is']
real
Enter fullscreen mode Exit fullscreen mode

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

Others

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

from time import *

# Current time in seconds
curr_time = time()
print(f'Current time in sec: {curr_time}')

# Formatted date and time
t = strftime("%A, %d %B %Y %H:%M:%S")
print(t)

----------
Current time in sec: 1685963439.6365585
Monday, 05 June 2023 16:40:39
Enter fullscreen mode Exit fullscreen mode

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


πŸ†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✌✌

πŸ’– πŸ’ͺ πŸ™… 🚩
sachingeek
Sachin

Posted on March 15, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related