zip_longest Pads Uneven Iterations

Keep uneven sequences aligned with zip_longest: fillvalue marks the missing side explicitly instead of letting zip truncate silently.

PythonData Integrity

Code

pythonsnippet
16 lines
from itertools import zip_longest

names = ['parse', 'render', 'upload']
durations = [12, 84]

# 普通 zip 按最短的截断:upload 被静默丢弃
print('zip      :', list(zip(names, durations)))

# zip_longest 补齐到最长:缺谁一目了然
print('padded   :', list(zip_longest(names, durations, fillvalue=0)))

# 补位值用哨兵标记缺失,后续统一处理
print('sentinel :', list(zip_longest(names, durations, fillvalue='MISSING')))

# 多个序列同样按最长对齐
print('three    :', list(zip_longest(names, durations, [True], fillvalue=None)))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

zip      : [('parse', 12), ('render', 84)]
padded   : [('parse', 12), ('render', 84), ('upload', 0)]
sentinel : [('parse', 12), ('render', 84), ('upload', 'MISSING')]
three    : [('parse', 12, True), ('render', 84, None), ('upload', None, None)]

How the file operates

Module-level bindings hold the data — names, durations — with no function scope in between.

Putting it to use

Running the file prints labeled results such as zip :, padded :, sentinel : — each operation’s effect is visible in the output.

Interactive Tools for This Topic

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. Every import resolves inside the standard library — `itertools`. Its state lives in module-level bindings: `names`, `durations`.