I propose introducing a new syntax for looping over two iterables simultaneously:
for i, j in a, b:
# do something with i and j
Current State:
As it stands, when we need to iterate over two lists (or other iterables) in parallel, we typically use the zip function:
for i, j in zip(a, b):
# do something with i and j
While this approach is perfectly functional, I believe a more direct and readable syntax could improve the clarity and elegance of the code.
Rationale:
-
Readability: The proposed syntax directly reflects the intention of iterating over two collections in parallel without the need to mentally parse the
zipfunction. This can be particularly helpful for beginners or when quickly scanning code. -
Conciseness: The proposed syntax is shorter and eliminates the need for an additional function call, making the code cleaner.
-
Consistency: Python strives for readability and simplicity. Enhancing the
forloop syntax in this manner aligns well with Python’s philosophy.
Example Comparison:
Current syntax with zip:
a = [1, 2, 3]
b = ['a', 'b', 'c']
for i, j in zip(a, b):
print(i, j)
Proposed syntax:
a = [1, 2, 3]
b = ['a', 'b', 'c']
for i, j in a, b:
print(i, j)
Both snippets would produce the same output:
1 a
2 b
3 c
Considerations:
- Backward Compatibility: This proposal does not break existing code since it introduces a new syntax.
- Implementation: The underlying implementation would essentially translate the new syntax to the existing
zip(a, b)construct.
I am keen to hear your thoughts and feedback on this idea. Do you think this enhancement would be beneficial? Are there any potential pitfalls I haven’t considered?
Looking forward to a constructive discussion.
by the way, it the first time I post on python forum, please notice me if I am offending any rule.