Enumerate And Zip Paired Iteration
Walk sequences with index and in parallel using enumerate and zip, replacing index arithmetic and off-by-one-prone range loops.
Code
def main() -> None:
names = ['alpha', 'beta', 'gamma']
scores = [9, 7, 8]
# enumerate:同时拿索引与值,从 1 起始直接做人读编号
for rank, name in enumerate(names, start=1):
print(f'{rank}. {name}')
# zip:并行遍历两个序列
for name, score in zip(names, scores):
print(f'{name}: {score}')
# zip + enumerate 组合:带名次与配对
ranked = sorted(zip(scores, names), reverse=True)
for rank, (score, name) in enumerate(ranked, 1):
print(f'#{rank} {name} ({score})')
# strict=True(3.10+):长度不等立即报错而非静默截断
try:
list(zip(names, [1, 2], strict=True))
except ValueError as exc:
print('strict zip caught:', exc)
if __name__ == '__main__':
main()Output
Captured from a sandboxed run of this snippet in the build pipeline.
1. alpha
2. beta
3. gamma
alpha: 9
beta: 7
gamma: 8
#1 alpha (9)
#2 gamma (8)
#3 beta (7)
strict zip caught: zip() argument 2 is shorter than argument 1How the snippet works
Enumerate And Zip Paired Iteration reduces to the function main.
Iteration happens inside for rank, name in enumerate(names, start=1) — everything outside it runs once.
Applying it
Entry signature: def main() -> None
Running the file prints labeled results such as strict zip caught: — each operation’s effect is visible in the output.
Statements that matter
except ValueError as exc:
print('strict zip caught:', exc)
Interactive Tools for This Topic
FAQ
- What does Enumerate And Zip Paired Iteration print when run?
- Run it as a complete program — the output lines carry labels such as `strict zip caught:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.