Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If we could use def func(*args), why is *args = (1,2) wrong?

Tags:

python

When I was learning the details of unpacking operation in python, I did some programming to practice. When I wrote: a, *b = (1,2,3), I got b = [2,3].

After doing this, I suddenly noticed the * operation also exists in python elsewhere, such as arbitrary argument in python functions. And I write:

def func(a, *args):
    for arg in args:
        print(arg)
func(1,2,3)

Output for this code was:

2
3

So I tried to figure out how this worked. This is how I think: when I called func(1,2,3), python interpreter would do the assignment: a, *args = 1, 2, 3, so a=1, args=[2,3]. But when I added print(type(args)) in func, the output was tuple. After doing this, I tested def func(*args) which worked as well. Even the type was not the expected one, but the elements in the args were.

Then, I did another test: *args=[1,2], but I got an Error, which is SyntaxError: starred assignment target must be in a list or tuple.

Now, I was confused about the * in the unpacking operation and the arbitrary argument. The question is what role does * play in these 2 situations?

I found that others also had doubts about expression like *args=[1,2,3], but they didn't mention the relation with arbitrary argument.

like image 440
stayfish Avatar asked Oct 29 '25 02:10

stayfish


1 Answers

You can do this:

*a, = (1,2,3)

or this

[*a] = (1,2,3)

essentially when you do

a, b = [1,2]

it is the same as

(a, b) = [1,2]

It is getting parsed as a tuple unpacking. When creating a tuple with a single element you need to add a comma at the end to prevent it from being parsed as a parenthetical: e.g. (a,) The same thing applied here. You need to add a comma when destructuring a single item to signify that you want tuple destructuring.

like image 82
Zachiah Avatar answered Oct 31 '25 15:10

Zachiah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!