Reputation: 1261
In the following codes there are two places which asterisk(*) is used :
Asterisk in function:
def function(*asterisk):
print(1, type(asterisk))
Asterisk in expressions:
a, *b = (1, 2, 3)
print(2, type(b))
a, *b = [1, 2, 3]
print(3, type(b))
I know the meaning of asterisk in functions and how it works.
My question is why asterisk in print number 1 has a tuple type whereas in print number 2 and 3 has a list type ?
Why python interprets function *parameter as tuple regardless of argument's type and interprets *variable as list regardless of assigned numbers' type in expressions?
In the end, are those * different operators?!
Upvotes: 3
Views: 189
Reputation: 140148
The unpacking in assignment (python 3 specific) is extended iterable unpacking (when the unpacking term refers to the right hand side, the variable that follows *
in the left hand side isn't unpacked, but created), whereas the other one (also available in python 2) is just positional argument unpacking.
The *
"operator" is very different in both cases. The fact that extended iterable unpacking creates a list
is probably designed so the caller can extend that list.
In parameter unpacking, it's better to have a fixed iterable like tuple
. Once again those are completely different mechanisms.
Upvotes: 1
Reputation: 280182
The devs just figured a list would be easier to process in the assignment case. Quoting the PEP for a, *b = ...
syntax:
After a short discussion on the python-3000 list [1], the PEP was accepted by Guido in its current form. Possible changes discussed were:
...
Make the starred target a tuple instead of a list. This would be consistent with a function's *args, but make further processing of the result harder.
And the mailing list discussion:
IMO, it's likely that you would like to further process the resulting sequence, including modifying it.
The mailing list discussion is pretty short (starts here, only 28 messages), so don't be afraid to read the whole thing.
Upvotes: 4