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.

PythonCli Tooling

Code

pythonsnippet
16 lines
# 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

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