为什么在 Python 中解包给出的是列表而不是元组?

Why does unpacking give a list instead of a tuple in Python?

这对我来说真的很奇怪,因为默认情况下我认为解包会给出元组。

在我的例子中,我想使用 prefix 键进行缓存,因此首选元组。

# The r.h.s is a tuple, equivalent to (True, True, 100)
*prefix, seed = ml_logger.get_parameters("Args.attn", "Args.memory_gate", "Args.seed")
assert type(prefix) is list

但我认为解包会 return 一个元组。

这里是相关的 PEP:https://www.python.org/dev/peps/pep-3132/

-- 更新--

鉴于下面的评论和答案,我特别期待解包给出一个元组,因为在函数参数中,展开的 arg 始终是一个元组而不是列表。

正如 Jason 指出的那样,在解包过程中,人们无法提前知道结果的长度,因此在实现方面,包罗万象必须从动态追加列表开始。大多数时候将其转换为列表是一种浪费。

从语义上讲,为了保持一致性,我更愿意使用元组。

这个问题 mentioned in that PEP (PEP 3132):

After a short discussion on the python-3000 list [1], the PEP was accepted by Guido in its current form. Possible changes discussed were: [...]

  • Try to give the starred target the same type as the source iterable, for example, b in a, *b = 'hello' would be assigned the string 'ello'. This may seem nice, but is impossible to get right consistently with all iterables.

  • 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.

但是如您所见,这些功能目前尚未实现:

In [1]: a, *b, c = 'Hello!'
In [2]: print(a, b, c)
H ['e', 'l', 'l', 'o'] !

也许,可变列表更适合这种类型的解包。