Meaning of asterisk here

At Stack Overflow there is code such as

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(10, size=(3,1)), columns=['A'])
df = df.reindex(columns=[*df.columns.tolist(), 'col1', 'col2'], fill_value=0)

What is the meaning of * in the 4th line? Thanks.

* unpacks a list. So if my_list = ["cat", "dog", "bird"] then *my_list would evaluate to "cat", "dog", "bird".

In the code you provided df.columns.tolist() returns a list, then the items are unpacked, extended with the additional items ‘col1’ and ‘col2’, and then all put into a new list (inside the square brackets).

1 Like

This is iterable unpacking:

>>> [*range(5,0,-1), "blast-off"]
[5, 4, 3, 2, 1, 'blast-off']
1 Like

this could have also been achieved by using df.columns.tolist().extend(['col1', 'col2'])

1 Like

Except that list.extend returns None because it is a method
modifying an object in place (modifies the list). That makes it hard to
embed concisely in an expression as in the OP’s example.

There’s always df.columns.tolist() + ['col1', 'col2'] though.

Cameron Simpson

1 Like

You’re right. I can’t tell you how many times this bites me, in-place list methods return None. Grrrr.

Better to be bitten than to have lurking bugs from mistakenly modified objects IMO.

1 Like