0

what seems to be the problem with the code

l = [1,2,4,5,6,7,8] t = *l 

i have read that *l gives comma separated single values so the statement should be similar to t = 1,2,3,4,5,6,7 which is a tuple but following code gives the error

Traceback (most recent call last): File "<main.py>", line 4 SyntaxError: can't use starred expression here 
4
  • 1
    "t=1,2,3,4,5,6,7 which is a tuple" what makes you think that? Commented Jan 17 at 18:23
  • 2
    @njzk2 Because it is Commented Jan 17 at 18:47
  • 1
    If you want to convert it to a tuple, use t = tuple(l) Commented Jan 17 at 18:52
  • Related: Python unpacking list: can't use starred expression Commented Jan 17 at 19:39

1 Answer 1

5

PEP 448, the PEP that introduced the kind of unpacking you're trying to do, specifically allows unpacking "inside tuple, list, set, and dictionary displays".

If you want to unpack l into a tuple on the RHS of an assignment, the unpacking has to happen in a "tuple display" - syntax that would have created a tuple even without the unpacking. l would not create a tuple, so your unpacking is invalid.

You can make the unpacking work with code like

t = *l, 

since t = l, would be valid syntax to create a one-element tuple.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.