What is the Asterisk / Star Operator (*) in Python?

5/5 - (6 votes)

Many Python coders—even at intermediate skill levels—are often puzzled when it comes to the asterisk character in Python. What does it mean? How does it work? What’s it purpose? This article answers all of those questions and more.

After studying this article, you will have a solid understanding of the asterisk operator * in Python—and become a better coder in the process!

** Reading time: 3:30 **

In a nutshell, the asterisk operator in Python has 6 different meanings:

  • a*b — Multiplication,
  • a**b Exponentiation,
  • [a] * b Creating container types,
  • def f(*args) Unpacking 1: Define an arbitrary number of positional arguments,
  • def f(**kwargs) Unpacking 2: Define an arbitrary number of keyword arguments, and
  • f(**dic) Unpacking a container type (e.g. dictionary).

Before you start learning, let’s open your knowledge gap first. Try out this interactive code shell:

Exercise: Guess the output of each asterisk example. Run the code to check if you guessed correctly.

Do you feel confident using the asterisk (star) operator? No? I thought so!

When to Use the Star * Operator in Python?

There are six different answers to this question:

1) Multiply Two Values

print(2 * 3)
# 6

This is how you have already used the star operator thousands of times in your own code.

2) Calculate the Power of a Value

print(2 ** 3)
# 8

Using the star operator to calculate the exponentiation of a value is a bit more unusual – but still very common. Simply use the expression x ** y to calculate โ€œx to the power of yโ€.

3) Create Container Data Types

lst = [999999] * 5
# [999999, 999999, 999999, 999999, 999999]

Creating lists by using the star operator is a handy feature. Keep it in mind and try to use it in your next projects (use it or lose it).

4) Create a Function with an Arbitrary Number of Positional Arguments

def average(*args):
    return sum(args) / len(args)

print(average(999.0, 966.3, 988.2, 1344.5))
# 1074.5

Finally, we reached a much more interesting use case of the star operator which you should understand thoroughly.

How to ensure that a function can take an arbitrary number of arguments? The function average in the example shows you how to do this with your function argument *args. The asterisk operator creates a sequence of values from an arbitrary number of positional arguments. It’s really this: it creates a new variable with the name args that is visible within the function.

The variable is of type tuple as you can see here:

def average(*args):
    return sum(args) / len(args)

print(average(999.0, 966.3, 988.2, 1344.5))
# 1074.5

5) Create a Function with an Arbitrary Number of Keyword Arguments

First of all, what are keyword arguments? They’re function arguments with a name (unlike positional arguments).

def likes(**kwargs):
    for key in kwargs:
        print(key + " likes " + kwargs[key])

likes(Alice="Bob", Bob="Ann", Ann="Alice")
# Alice likes Bob
# Bob likes Ann
# Ann likes Alice

In the example, we pass three keyword arguments when calling the function likes(...) with names: Alice, Bob, and Ann. The double asterisk operator ** before the variable kwargs packs all these arguments (and potentially more) into a dictionary named kwargs.

Try it yourself: run print(type(kwargs)) within your function and the interpreter will tell you that the variable is of type dict.

Now, you can conveniently access the keyword arguments within your function (using the variable name kwargs).

We call case 4) and 5) UNPACKING of the arguments. Why unpacking? Because they are unpacked within the argument. What is the packed form then? You can get the packed form when leaving away the asterisk operator(s). For example, the values in args or kwargs are packed within a container data type (i.e., a tuple in case 4) and dictionary in case 5.

6) Unpack a Dictionary

def likes(**kwargs):
    for key in kwargs:
        print(key + " likes " + kwargs[key])

dic = {"Alice" : "Bob",
       "Bob" : "Ann",
       "Ann" : "Alice"}
# Alice likes Bob
# Bob likes Ann
# Ann likes Alice

Now that you know about unpacking, it’s easy to see what is going on here. You create a dictionary dic. The dictionary contains the keyword arguments — but they are still packed within the dictionary. To unpack them, you use the double asterisk operator when calling the function.

Think of it this way: If you wanted to define the values in the dictionary, you would write them without the curly bracket notation {}. To remove the bracket, you use the double asterisk operator **.

Train Your Unpacking Skills!

At this point, you have learned about the asterisk (star) operator in Python. Use the asterisk operator to unpack a container data type such as a list or a dictionary.

Let’s practice unpacking a bit. Here is the most basic form of unpacking:

readers = ["Cata", "Brian", "Myu", "Joey"]

# ['Cata', 'Brian', 'Myu', 'Joey']

# Cata Brian Myu Joey

As you can see, the asterisk operator basically removes the wrapper data type (i.e., the list). Here is how you can use simple unpacking when calling a function with positional arguments:

def say_hello(*args):
    for arg in args:
        print("hello " + arg)

readers = ["Cata", "Brian", "Myu", "Joey"]
hello Cata
hello Brian
hello Myu
hello Joey

The four list values “unpack” in the functional argument by passing it with *readers. Within the function argument, they exist in unpacked form.

In the function definition, you can see another application of the asterisk operator: arbitrary arguments.

Logically — if you put the asterisk operator before the argument name (*args) when defining the function — you tell it that the arguments are already unpacked. In other words, the expression *args contains the values in an unpacked form. Thus, the expression args (without the asterisk) refers to the packed form of these values. This is why you can use args in your function just like a normal list.

How does that look like for dictionaries?

elos = {"Alice" : 1988,
        "Bob" : 2253,
        "Frank" : 1574}

# {'Alice': 1988, 'Bob': 2253, 'Frank': 1574}

# Alice Bob Frank

If you unpack a dictionary with the single asterisk operator, the result is the unpacked form of the dictionary’s keys.

Now, how do we unpack the dictionary’s (key, value) pairs (and not only the keys)? By using the double asterisk operator!

def print_masters(**kwargs):
    for key in kwargs:
        if kwargs[key] > 2000:
            print(str(key) + " " + str(kwargs[key]))

elos = {"Alice" : 1988,
        "Bob" : 2253,
        "Frank" : 1574}

# Bob 2253

Now, here is a nice way of using this feature to merge two dictionaries by unpacking both into a new dictionary…

elos_1 = {"Alice" : 1988,
        "Bob" : 2253}

elos_2 = {"Pete" : 1324,
        "Frank" : 1574}

elos = {**elos_1, **elos_2}
# {'Alice': 1988, 'Bob': 2253, 'Pete': 1324, 'Frank': 1574}

What a beautiful Python feature! ๐Ÿ˜€

Frequently asked questions

What are keyword arguments in Python?

All function arguments have names (=keywords). When calling the function, you have two choices: use positional arguments or keyword arguments. In contrast to positional arguments, keyword arguments make the names explicit when calling the function. Using keyword arguments, you donโ€™t need to care about the order of the arguments.

Here is an example:

def minus(a, b, c): # all arguments are named
    print(a - b - c)

# positional arguments:
# 0

# keyword arguments:
minus(c=1, b=2, a=3)
# 0 (keyword overwrites order / position)

Why is **kwargs used in Python?

The expression **kwargs is used when defining a function to indicate that you can call this function with an arbitrary number of keyword arguments. Here is an example:

def likes(**kwargs):
    for key in kwargs:
        print(str(key) + " likes " + str(kwargs[key]))

" Alice likes Bob"

likes(Alice="Bob", Bob="Alice")
Alice likes Bob
Bob likes Alice

likes(Alice="Bob", Bob="Alice", spam=42)
Alice likes Bob
Bob likes Alice
spam likes 42

As you can see, we can call the function with an arbitrary number of keyword arguments.

What is the meaning of the asterisk operator for Python regular expressions?

Every computer scientist knows the asterisk quantifier of regular expressions. But many non-techies know it, too. Each time you search for a text file *.txt on your computer, you use the asterisk operator.

Python Re * โ€“ The Asterisk Quantifier for Regular Expressions

When applied to regular expression A, Python’s A* quantifier matches zero or more occurrences of A. The * quantifier is called asterisk operator and it always applies only to the preceding regular expression. For example, the regular expression ‘yes*’ matches strings ‘ye’, ‘yes’, and ‘yesssssss’. But it does not match the empty string because the asterisk quantifier * does not apply to the whole regex ‘yes’ but only to the preceding regex ‘s’.

Let’s study two basic examples to help you gain a deeper understanding. Do you get all of them?

>>> import re
>>> text = 'finxter for fast and fun python learning'
>>> re.findall('f.* ', text)
['finxter for fast and fun python ']
>>> re.findall('f.*? ', text)
['finxter ', 'for ', 'fast ', 'fun ']
>>> re.findall('f[a-z]*', text)
['finxter', 'for', 'fast', 'fun']

If you struggle with understanding the Python regex asterisk operator in these examples, read the following tutorial:

Related tutorial: Python Re * – The Asterisk Quantifier for Regular Expressions

Where to Go From Here?

Enough theory. Letโ€™s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. Thatโ€™s how you polish the skills you really need in practice. After all, whatโ€™s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

๐Ÿš€ If your answer is YES!, consider becoming a Python freelance developer! Itโ€™s the best way of approaching the task of improving your Python skillsโ€”even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar โ€œHow to Build Your High-Income Skill Pythonโ€ and learn how I grew my coding business online and how you can, tooโ€”from the comfort of your own home.

Join the free webinar now!