Starred Unpacking Splits Head And Tail
Extended unpacking assigns first, *middle, last in one statement, and the starred slot absorbs zero or more items, so it never raises on short sequences.
Code
values = [3, 9, 4, 7, 5, 8]
# 星号槽吞下中间任意多项:头尾各取一个
first, *middle, last = values
print(first, middle, last)
# 序列太短也不抛错:星号槽允许为空
head, *rest = ["only-one"]
print(head, rest)
# 星号槽前也可以有多个固定槽位
a, b, *others = [1, 2, 3, 4]
print(a, b, others)
# 同一语法在函数签名里收集多余位置参数
def send(subject, *recipients):
return f"{subject} -> {len(recipients)}"
print(send("deploy", "ada", "li", "sam"))Output
Captured from a sandboxed run of this snippet in the build pipeline.
3 [9, 4, 7, 5] 8
only-one []
1 2 [3, 4]
deploy -> 3How the snippet works
Starred Unpacking Splits Head And Tail is built around the function send.
Applying it
The main signature reads def send(subject, *recipients)
Import send from the file and call it — the rest of the code is implementation detail.
Statements that matter
def send(subject, *recipients):
return f"{subject} -> {len(recipients)}"
Interactive Tools for This Topic
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. The file defines `send` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.