tuples - List unpacking in python - Stack Overflow

what seems to be the problem with the codel = [1,2,4,5,6,7,8]t = *li have read that *l gives comma se

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

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
Share Improve this question edited Jan 17 at 18:47 wjandrea 33.3k10 gold badges69 silver badges98 bronze badges asked Jan 17 at 18:21 Sachin DobhalSachin Dobhal 213 bronze badges 4
  • 1 "t=1,2,3,4,5,6,7 which is a tuple" what makes you think that? – njzk2 Commented Jan 17 at 18:23
  • 2 @njzk2 Because it is – wjandrea Commented Jan 17 at 18:47
  • 1 If you want to convert it to a tuple, use t = tuple(l) – Barmar Commented Jan 17 at 18:52
  • Related: Python unpacking list: can't use starred expression – wjandrea Commented Jan 17 at 19:39
Add a comment  | 

1 Answer 1

Reset to default 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745349155a4623721.html

相关推荐

  • tuples - List unpacking in python - Stack Overflow

    what seems to be the problem with the codel = [1,2,4,5,6,7,8]t = *li have read that *l gives comma se

    1天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信