1

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???

miken32
  • 42,008
  • 16
  • 111
  • 154
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • i don't know if that is exactly the case, because for example `*L,` will output the tuple, i'd have to look further into the grammar though. also related: https://stackoverflow.com/questions/40676085/why-cant-i-use-a-starred-expression – jmunsch Sep 16 '18 at 00:55
  • 3
    What exactly don't you understand? `*L` is not a valid expression. It is incomplete at best. What did you *expect* `*L` to do? – juanpa.arrivillaga Sep 16 '18 at 01:36

2 Answers2

2

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.

Jonas Wolff
  • 2,034
  • 1
  • 12
  • 17
  • 1
    I don't think `repr` is relevant here. The REPL evaluates the expression, and prints the `repr` of that expression, yes. But it is the evaluation of the expression that is failing – juanpa.arrivillaga Sep 16 '18 at 01:35
  • are you sure? i will happily delete the post if you are – Jonas Wolff Sep 16 '18 at 01:36
  • 1
    Yes. This isn't throwing any exception regarding passing an incorrect amount of arguments, it's clearly a `SyntaxError` and that's because `*l` is not syntactically correct – juanpa.arrivillaga Sep 16 '18 at 01:42
1

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.

Sraw
  • 18,892
  • 11
  • 54
  • 87