enumerate Yields Index And Item
Loop with index and item together using enumerate: start shifts the numbering for human ranks, and list materializes index-item tuples.
Code
# enumerate 同时给出下标与元素:不用手动维护 i += 1
languages = ['python', 'javascript', 'go']
for position, name in enumerate(languages):
print(position, name)
# start=1 让编号符合人类习惯(榜单、菜单),下标逻辑不受影响
for rank, name in enumerate(languages, start=1):
print(f'{rank}. {name}')
# 枚举结果可再消费:list 化后是 (下标, 元素) 元组
print(list(enumerate(languages, start=100)))
# 直接构造有序映射:下标即键
priority = {name: i for i, name in enumerate(languages, start=1)}
print('priority:', priority)Output
Captured from a sandboxed run of this snippet in the build pipeline.
0 python
1 javascript
2 go
1. python
2. javascript
3. go
[(100, 'python'), (101, 'javascript'), (102, 'go')]
priority: {'python': 1, 'javascript': 2, 'go': 3}What the code does
Repetition is confined to for position, name in enumerate(languages) — the rest of the file is straight-line.
Top-level bindings languages, priority hold the demo state — nothing sits inside a function scope.
Using it
The demo output is labeled (priority:); each label names the call that printed it.
Key statements
priority = {name: i for i, name in enumerate(languages, start=1)}
for rank, name in enumerate(languages, start=1):
print(f'{rank}. {name}')
for position, name in enumerate(languages):
print(position, name)
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Its state lives in module-level bindings: `languages`, `priority`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.