Skip to Content

What Does Asterisk Before Variable Mean In Python?

What Does Asterisk Before Variable Mean In Python?

What does the asterisk before a variable name mean in Python? For example, if I have a variable that contains a list of strings and the name of the variable is called my_list what does *my_list do?

The asterisk is an operator in Python that is commonly known as the multiplication symbol when used between two numbers (2 * 3 will produce 6) but when it is inserted at the beginning of a variable, such as an iterable, like a list or dictionary, it expands the contents of that variable.

Here’s an example of a variable containing a list of strings and what happens when you apply the * operator:

>>> my_list = ["A", "B", "C"]
>>> print(*my_list, sep="\n")
A
B
C

As you can see from the example above the print() function produces each of the elements in the original list of strings and each item in the list is output with the new line character appended.

Where else can this be used?

Short-Cut Method To Read Lines From A File

You can similarly use the asterisk operator when expanding lines from a file.

For example, suppose I had a file called sample.txt and the contents of this file were something simple like:

A1
B2
C3

Prior to using the asterisk operator to process each line of the file I wrote some familiar code like this:

with open('sample.txt') as f:
    for line in f:
        print(line)

The result of this code produced the output:

A1
B2
C3

However, upon discovering the power of the asterisk operator and its ability to output each of the components within a variable, I applied the same operation to opening the file, and achieved the same result through fewer lines of code, as seen here:

with open('sample.txt') as f:
    print(*f, sep='\n')

Which produced:

A1
B2
C3

This output the same result without needing the for loop!

Besides expanding the components within a list or file, does the asterisk operator also perform on other items like strings, dictionaries or tuples?

Asterisk Operator On Strings

Does the asterisk operator work on variables that contain strings?

Let’s have a look in the Python REPL:

>>> my_string = "Star"
>>> print(*my_string, sep="\n")
S
t
a
r

Wow! It even works on strings outputting each character as a separate element within a string.

Asterisk Operator On Dictionaries

Does the asterisk operator work on variables that contain dictionaries?

Again, let’s explore this in the Python REPL and give it a spin:

>>> my_dict = {"a": 1, "b": 2, "c": 3}
>>> print(*my_dict, sep="\n")
a
b
c

Interestingly the asterisk operator performed on the dictionary provides the keys.

What would happen if the dictionary were nested?

>>> my_dict = {"a": 1, "b": { "b1": 21, "b2": 22 }, "c": 3}
>>> print(*my_dict, sep="\n")
a
b
c

As before it just produces the top-level keys of the dictionary, not any nested keys.

Asterisk Operator On Tuples

How does the asterisk operator work on tuples? I would expect the behaviour to be somewhat similar to how it performs with a list.

>>> my_tuple = ("A", "B", "C")
>>> print(*my_tuple, sep="\n")
A
B
C

As expected the asterisk operator provides each element within the tuple separately.

What Does An Asterisk Parameter Mean?

Some functions in Python such as the zip function have a parameter that in has an asterisk on the parameter name.

According to the zip documentation on Python’s website the first parameter *iterables has a single asterisk in front, what does this mean?

This would mean the first parameter can be made up of multiple parameters. I recently explored the zip function by zipping two or more lists and noted that the zip function can take a lot of lists. With each list passed in it could zip them all up into one list from each corresponding index in every list (provided the lists were the same length).

For example, here’s what would happen if I passed in four lists into the zip() function:

>>> list(zip([1, 2], ["A", "B"], ["a", "b"], ["!", "@"]))
[(1, 'A', 'a', '!'), (2, 'B', 'b', '@')]

Therefore, without reading the source code behind the zip() function I can understand that because the first parameter *iterables contains an asterisk at the front of the variable name that the function can take more than 1 value – hence, why the example above I passed through 4 lists and the function didn’t break.

Create Your Own Asterisk Parameter Function

Sum Function That Takes Multiple Numbers

One simple way to demonstrate how you can create your own function containing an asterisk parameter is to perform a simple sum on a series of numbers passed in.

For example, currently the built-in sum() function does not permit more than 2 parameters, as evidenced by the following REPL result:

>>> sum(1, 2, 3)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: sum() takes at most 2 arguments (3 given)

As you can see the built-in function sum() from the error provided only takes at most 2 arguments. Can you rescue the sum() function by enabling it to sum 3 or more values passed in?

Let’s use the asterisk operator!

Here’s one way of being able to use the asterisk operator on a custom function when it’s defined as the parameter:

>>> def my_sum(*values):
...     return sum(values)
...
>>> my_sum(1, 2, 3)
6

Look at that!

It doesn’t matter how many values I enter in my function my_sum() it will correctly add them all by using the asterisk operator on the sole parameter.

The reason why this code works is that each parameter passed into the my_sum() function is received by that function as a tuple. Therefore, when calling the function as my_sum(1, 2, 3) it is received by that function and stored as the variable values as a tuple (1, 2, 3).

As this is the sole iterable being passed into the built-in function sum() it then adds each value within the tuple providing the result that you desire! Win-win for everyone!

Summary

The asterisk operator expands each of the elements contained within an object that can be comprised of smaller elements. For example, a string is comprised of smaller elements known as characters, lists and tuples are comprised of items, dictionaries with keys and value pairs.

By using the asterisk operator on variables containing elements that can be expanded you can abbreviate your code or expand your functions even more by accepting more than one value from one parameter name.

Next, you might want to look at Python’s ** operator and how this can help to shortcut power calculations.