You will sometimes come across examples of code that use one or two asterisks. Depending on how the asterisks are used, they can mean different things to Python.
Check your understanding of what a single asterisk means in the following quiz!
What will be the output if you run this code?
numbers = range(3)
output = {*numbers}
print(output)
A) {range}
B) (range)
C) [0, 1, 2]
D) (0, 1, 2)
E) {0, 1, 2}
“Unpacking generalizations” is the term to look up if you get stuck..

E) {0, 1, 2}
A single asterisk before a Python dictionary or list is known as the unpacking operator. In this example, you tell Python to unpack three integers (0 – 2) into a set.
Here is the example running in a REPL:
>>> numbers = range(3)
>>> output = {*numbers}
>>> print(output)
{0, 1, 2}
>>> print(type(output))
<class 'set'>
The code output shows that you have created a set!
You can also use a single asterisk to unpack a dictionary’s keys:
>>> my_dict = {1: "one", 2: "two", 3: "three"}
>>> print({*my_dict})
{1, 2, 3}
If you want to take your knowledge of unpacking further, it can help to see Python functions use asterisks:
>>> def my_func(*args):
... print(args)
...
>>> my_func(1)
(1,)
>>> numbers = range(3)
>>> output = {*numbers}
>>> my_func(output)
({0, 1, 2},)
>>> my_func(*output)
(0, 1, 2)
When you see a single asterisk in a function definition, the asterisk means that the function can take an unlimited number of arguments. In the second example, you pass in the set as a single argument, while in the last example, you use a single asterisk to unpack the numbers and pass them in as three separate arguments.
For more information, see PEP 448 – Additional Unpacking Generalizations, which has many more examples!
Get the Book
Want to try out over one HUNDRED more quizzes? Check out the book!
