What are the Asterisks or Star Symbols '*' and '**' in Python?

Gain a solid understanding of the various ways you can use the asterisk or star * symbol

Picture of Nsikak Imoh, author of Macsika Blog
A blank paghe with the texts What are the Asterisks or Star Symbols '*' and '**' in Python?
A blank paghe with the texts What are the Asterisks or Star Symbols '*' and '**' in Python?

Table of Content

When you've been exposed to Python codes, you would have come across one or more of the asterisk symbols '*' or '**'.

As confusing and almost irrelevant as they might look, they are actually a really important part of Python programming.

Good knowledge of them might help you write efficient and more generic solutions when solving problems using Python language. Think of the DRY principle.

The asterisk (star) operator is used in Python with more than one meaning attached to it.

After going through this article, you will gain a solid understanding of the various ways you can use the asterisk or star * symbol and the counterpart double-asterisk or double-star * symbol in Python programming.

What are the Asterisks or Star Symbols * and ** in Python?

The single asterisk or star (*) and the double-asterisk or double-star (**) symbols are both used primarily for numeric multiplication and exponential calculation respectively in Python.

They also hold the same conventional use case in other programming languages.

5 Different Ways to Use the Asterisks or Star Symbols '*' and '**' in Python

In Python programming language, the single asterisk or star (*) and the double-asterisk or double-star (**) symbols can be used for other functionality that is different from the conventional use case.

Here are five different ways you can use them in Python programming:

1. Perform calculations on numeric data types

This is more conventional use in programming.

In Python programming language, as with most programming languages, the single asterisk or star symbol (*) is used as a multiplication operator to get the product of two numeric values or variables.

a = 10
    b = 00
    a * b
    # 100
    
Highlighted code sample.

The double asterisk or star symbol (**) is used as an exponential operator and is used to raise the value or variable on the left to the power of the value or variable on the right.

a = 10
    b = 00
    a ** b
    # 10_000_000_000
    
Highlighted code sample.

2. Unpack an arbitrary number of arguments in a function parameter

There is a chance you should have come across the *args and **kwargs in a function argument in Python codes.

def func(*args, **kwargs):  
        pass
    
Highlighted code sample.

These symbols specify that the function could receive an unspecified and a possibly unlimited number of arguments or keyword arguments.

If you are not sure how many arguments and keyword arguments will be passed, you can use a single asterisk or star (*) and the double-asterisk or double-star (**) symbols, respectively.

For arguments, the values are received as a tuple and all properties of a tuple can be performed on it:

def get_student_names(*names):
        for n in names:
            print(n)
    
    get_student_names('Nsikak', 'Imoh', 'Archangel', 'Macsika')
    
    # Nsikak
    # Imoh
    # Archangel
    # Macsika
    
Highlighted code sample.

You can also pass the arguments as a list, tuple, or set. For a dictionary, to pass the keys only, use *, to pass the values only, use **.

def get_student_names(*names):
        for n in names:
            print(n)
    
    names = ['Nsikak', 'Imoh', 'Archangel', 'Macsika']
    get_student_names(*names)
    
    # Nsikak
    # Imoh
    # Archangel
    # Macsika
    
Highlighted code sample.

For keyword arguments, the values are received as a dictionary, and all properties of a dictionary can be performed on it:

def get_student_names(**names):
        for k,v in names.items():
            print(f"{k} - {v})
    
    get_student_names(n1='Nsikak', n2='Imoh', n3='Archangel', n4='Macsika')
    
    # n1 - Nsikak
    # n2 - Imoh
    # n3 - Archangel
    # n4 - Macsika
    
Highlighted code sample.

Passing as dictionary vs passing as keyword arguments for dict type.

# Passing as keyword arguments
    
    def get_student_names(**kwargs):  
        for item in kwargs:  
            print(f"{item} is {kwargs[item]}")  
              
    get_student_names(n1="Nsikak",n2="Imoh")
    # n1 is Nsikak
    # n2 is Imoh
    -----
    
    
    # Passing as Dictionary
    
    def get_student_names(**kwargs):  
        for item in kwargs:  
            print(f"{item} is {kwargs[item]}")  
                  
        dict_list = {"n1": "Nsikak", "n2": "Imoh"}
        get_student_names(**dict_list)
        # n1 is Nsikak
        # n2 is Imoh
    
Highlighted code sample.

3. Force all arguments passed to a function to be keyword-only arguments

Another way we can use an asterisk in a function is to ensure that a function can only receive keyword arguments.

To do that, simply pass a single asterisk or star * in the parameter list and the following arguments must be passed as keyword arguments.

def get_student_names(*, first_name, last_name):
        print(first_name, last_name)
        
    get_student_names('Nsikak', 'Imoh')  
    # TypeError: get_student_names() takes 0 positional arguments but 2 were given 
    
    get_student_names(first_name='Nsikak', last_name='Imoh')
    # Nsikak Imoh
    
Highlighted code sample.

Also, we can restrict a few arguments to be keyword-only by just putting the positional arguments before the asterisk.

def get_student_names(grade, *, first_name, last_name):
        print(first_name, last_name, " ", grade)
        
    get_student_names("A", first_name='Nsikak', last_name='Imoh')
    # Nsikak Imoh
    
Highlighted code sample.

4. Unpack Elements of an iterable into a new iterable

One way we can use asterisks to make our programs clear and elegant is when we need to combine different iterable such as lists, tuples, and sets into a new list.

An obvious solution for this is to use for-loops to iterate all items and add them to a new list one after the other.

A = [1, 2, 3]
    B = (4, 5, 6)
    C = {7, 8, 9}
    
    new_list = []
    
    for a in A:
        new_list.append(a)
    
    for b in B:
        new_list.append(b)
    
    for c in C:
        new_list.append(c)
    
    print(new_list)
    # [1, 2, 3, 4, 5, 6, 8, 9, 7]
    
Highlighted code sample.

Even though the code block above accomplishes our mission, the code looks so long and is not very “Pythonic”.

We could use list comprehensions to make the code a lot better.

A = [1, 2, 3]
    B = (4, 5, 6)
    C = {7, 8, 9}
    
    new_list = [a for a in A] + [b for b in B] + [c for c in C]
    
    print(new_list)
    # [1, 2, 3, 4, 5, 6, 8, 9, 7]
    
Highlighted code sample.

Using list comprehension takes us a step closer to achieving a great solution, but we can do even better than that by using asterisks.

A = [1, 2, 3]
    B = (4, 5, 6)
    C = {7, 8, 9}
    
    new_list = [*A, *B, *C]
    
    print(new_list)
    # [1, 2, 3, 4, 5, 6, 8, 9, 7]
    
Highlighted code sample.

This method works really well for iterable such as lists, tuples, and sets.

However, it's different for dictionaries.

If we use a single asterisk * as a prefix to unpack dict, its keys will be unpacked. And if we use double asterisks ** as a prefix, its values will be unpacked.

But, we need the keys of a dictionary to receive the unpacked values, which makes unpacking a dictionary to be inconvenient and uncommon.

Extended unpacking of Iterable

In Python 3, it is possible to use `*l` on the left side of an assignment as an Extended Iterable Unpacking proposed in PEP 3132.

However, the variable with the '*' becomes a list instead of a tuple in this context:

numbers = [1, 2, 3, 4, 5, 6]
    
    # The left side of unpacking should be a list or tuple.
    
    *a, = numbers
    # a = [1, 2, 3, 4, 5, 6]
    
    *a, b = numbers
    # a = [1, 2, 3, 4, 5]
    
    # b = 6
    a, *b, = numbers
    
    # a = 1
    # b = [2, 3, 4, 5, 6]
    
    a, *b, c = numbers
    # a = 1
    
    # b = [2, 3, 4, 5]
    # c = 6
    
Highlighted code sample.

5. Repeat a string multiple times

The single asterisk (*) can be used to repeat values of variables in sequences such as string, list, and tuple.

s = "Nsikak" 
    print(s*3)
    'NsikakNsikakNsikak'
    
    list_1 = [1, 2, 3]
    print(list_1 * 3)
    # [1, 2, 3, 1, 2, 3, 1, 2, 3]
    
    tuple_1 = (1,2,3)
    print(tuple_1*3)
    # (1, 2, 3, 1, 2, 3, 1, 2, 3)
    
Highlighted code sample.

Wrap Off

So far, we've covered the Asterisk(*) of Python. It was interesting to be able to do various operations with one operator, and most of those above are the basics for writing Pythonic code.

We. hope you've gained a solid understanding of the various ways you can use the asterisk or star * symbol and the counterpart double-asterisk or double-star * symbol in Python programming.

If you learned from this tutorial, or it helped you in any way, please consider sharing and subscribing to our newsletter.

Please share this post and for more insightful posts on business, technology, engineering, history, and marketing, subscribe to our newsletter.

Get the Complete Code of Python Code Snippets on Github.

Connect with me.

Need an engineer on your team to grease an idea, build a great product, grow a business or just sip tea and share a laugh?