Basically my title is the question:
Example:
>>> l=[1,2,3]
>>> *l
SyntaxError: can't use starred expression here
>>> print(*l)
1 2 3
>>>
Why is that???
Basically my title is the question:
Example:
>>> l=[1,2,3]
>>> *l
SyntaxError: can't use starred expression here
>>> print(*l)
1 2 3
>>>
Why is that???
because it's equivalent to positional arugments corspondent to the list, so when your not calling it somewhere that can take all the arguments, it makes no sense, since there are nowhere to put the arguments
f.x.
print(*[1,2,3])
# is the same as
print(1,2,3)
and
*[1,2,3]
#is the same as - and do not think of it as a tuple
1,2,3 # here how ever that makes it a tuple since tuples not defined by the parenthasies, but the point is the same
there is however a slight exception to this which is in tuple, list, set and dictionaries as of python 3.5 but that is an exception, and can also be used to assign left over values, how ever python can see your doing non of these.
EDIT I undeleted my answer since i realised only the last part was wrong.
I think this is actually a question about understanding *l
or generally *ListLikeObject
.
The critical point is *ListLikeObject
is not a valid expression individually. It doesn't mean "Oh please unpack the list".
An example can be 2 *[1, 2, 3]
(As we all know, it will output [1, 2, 3, 1, 2, 3]
). If an individual *[1, 2, 3]
is valid, what should it output? Should it raise a runtime exception as the evaluated expression is 2 1 2 3
and it is invalid(Somehow like divided by 0)?
So basically, *[1, 2, 3]
is just a syntax sugar that helps you to pass arguments. You don't need to manually unpack the list but the interpreter will do it for you. But essentially it is still passing three arguments instead of one tuple of something else.