What Asterisk (*) Can Do In Python
Tags: python
Published: 2024-03-15 08:33:29

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.

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

---------
63
```

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.

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

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

----------
GeekGeekGeekGeekGeek
```

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

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

----------
256
```

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.

```python
# 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)
```

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](https://geekpython.in/understanding-args-and-kwargs-in-python-best-practices-and-guide) 

### Argument Packing

**Passing variadic positional arguments**

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

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

----------
('Rishu', 'Yashwant', 'Abhishek', 'Yogesh')
```

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**

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

# Passing variadic keyword arguments
names = friends(f1="Rishu", f2="Yashwant", f3="Abhishek")
print(names)
```

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

```python
# 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)
```

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.

```bash
Welcome to GeekPython, Sachin.
Welcome to GeekPython, Rishu.
Welcome to GeekPython, Yashwant.
Welcome to GeekPython, Abhishek.
```

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

```python
message = greet(names_lst)

----------
Welcome to GeekPython, ['Sachin', 'Rishu', 'Yashwant', 'Abhishek'].
```

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

```python
# 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)
```

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.

```bash
Sachin is a Python dev.
Rishu is a C++ dev.
Yashwant is a C++ dev.
Abhishek is a PHP dev.
```

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

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

----------
Sachin is a Python dev.
Rishu is a C++ dev.
```

## 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.

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

print("-" * 20)

lst_data = ["Geek", "Python"] * 3
print(lst_data)
```

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.

```bash
GeekPythonGeekPythonGeekPython
--------------------
['Geek', 'Python', 'Geek', 'Python', 'Geek', 'Python']
```

## 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.

```python
# Using asterisk in string formatting

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

# Unpacking tuple
val = "{} {} {}.".format(*(1, 2, 3))
print(val)
```

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

```bash
Welcome to GeekPython.
1 2 3.
```

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.

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

----------
<class 'set'>
One real is piece
```

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.

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

----------
One
['piece', 'is']
real
```

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.

```python
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
```

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](https://geekpython.in/init-vs-new).

✅[An improved and modern way of string formatting](https://geekpython.in/f-string-in-python).

✅[Public, Protected, and Private access modifiers in Python](https://geekpython.in/access-modifiers-in-python).

✅[What are inheritance and different types of inheritance in Python](https://geekpython.in/class-inheritance-in-python)?

✅[What do they do - \_\_init\_\_ and \_\_call\_\_ methods](https://geekpython.in/init-and-call-method)?

✅[How to implement \_\_getitem\_\_, \_\_setitem\_\_, and \_\_delitem\_\_ in Python class](https://geekpython.in/implement-getitem-setitem-and-delitem-in-python)?

✅[Displaying images on the frontend using FastAPI](https://geekpython.in/displaying-images-on-the-frontend-using-fastapi).

---

**That's all for now**

**Keep Coding✌✌**