names = ["Alice", "Bob", "Charlie"]
counts = [len(n) for n in names]
print(counts)[5, 3, 7]
zip to Process Iterators in Parallelcountsenumerate or range to perform an index-based lookup
names = ["Alice", "Bob", "Charlie"]
counts = [len(n) for n in names]
# Range-based loop
longest_name = None
max_count = 0
for i in range(len(names)):
count = counts[i]
if count > max_count:
longest_name = names[i]
max_count = count
print(f"Longest name (range-based loop): {longest_name}")
longest_name = None
max_count = 0
for i, name in enumerate(names):
count = counts[i]
if count > max_count:
longest_name = name
max_count = count
print(f"Longest name (enumerate-based approach): {longest_name}")Longest name (range-based loop): Charlie
Longest name (enumerate-based approach): Charlie
enumerate method is cleaner
names listcounts but not nameszip operator
zip wraps multiple iterators in a lazy generatorenumeratezip consumes elements one at a time from each iteratorzip stops yielding when any of the wrapped iterators are exhausted
Alice: 5
Bob: 3
Charlie: 7
zip supports the strict keyword argument
False default behaviour is assumedTrue a ValueError is raised if zip exhausts one of the iterators Alice: 5
Bob: 3
Charlie: 7
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[5], line 6 2 counts = [len(n) for n in names] 4 names.append("Danielle") ----> 6 for name, count in zip(names, counts, strict=True): 7 print(f" {name}: {count}") ValueError: zip() argument 2 is shorter than argument 1
strict is designed for providing a run time check that the iterators are of the same length
zip_longest from the itertools built-in module
None)zip is a built-in function for iterating over multiple iterators in parallelzip creates a lazy generator returning tuples
zip silently truncates the length of the shortest wrapped iteratorstrict keyword is introduced in python 3.10
ValueError