How do I loop through a tuple of lists element-wise?

Question:

I have a function that returns a tuple of two lists

def two_lists():
    return [1, 2, 3], ['a', 'b', 'c']

I want to loop through the tuple in a manner similar to this

for v1, v2 in two_lists():
   print v1, v2

output:
    1, a
    2, b
    3, c

The only way I have found I find rather cumbersome!

a, b = two_lists()
for i, y in zip(a, b):
    print i, y

Is there a prettier more pythonic way to achieve this?

Asked By: JonB

||

Answers:

Sure, you can directly unpack two_lists() in your zip call.

for i, y in zip(*two_lists()):
    print i, y

This is the idiomatic way to do this.

Answered By: Morgan Thrapp
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.