Understand List Star Operator (*List) in Python – Python Tutorial

By | May 29, 2023

We may see some *list operation in python script. In this tutorial, we will introduce what it is and how to use it.

Look at this example:

data = []
for i in range(10):
    data.append(i)
x = *data

Run this code, we will see: SyntaxError: can’t use starred expression here

Here data is a python list, however, this error means we can not use *data directly.

data = []
for i in range(10):
    data.append(i)
x = ["abc", *data]

print(x)

Run this code, we will get:

['abc', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

We find *data will unpack the python data list.

Morever, look at this code below:

def show(*x):
    print(type(x))
    print(x)

show(*data)

Run it, we will see:

<class 'tuple'>
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

We find x is a tuple, which means that *data allows to get each element from python list data and save them to a python tuple.

We may also see *args in some python function, it is also python list with star operation.

Understand Python *args Parameter: A Beginner Guide – Python Tutorial