0

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?

Rick
  • 43,029
  • 15
  • 76
  • 119
JonB
  • 804
  • 3
  • 12
  • 40
  • If you want to make it terser, you can just do `for i, y in zip(*two_lists())`, which will upack the tuple in-place. Otherwise, if you're trying to say `zip` is un-pythonic, I would disagree. – user3030010 Oct 06 '16 at 18:57
  • Edited to add Python 2 tag. – Rick Oct 06 '16 at 19:21
  • 5
    Please, please, please do not use list comprehensions for their side effects. It's incredibly bad practice and inefficient. There is never a time when that is the correct solution. – Morgan Thrapp Oct 06 '16 at 19:26
  • 3
    So, having a resulting list with `[None, None, None, None]` is OK? That doesn't seem like the best advice here. I would advise against using that list comp solution. – idjaw Oct 06 '16 at 19:28
  • Another nice python 3 way of doing it (Python 3.5 or higher only), which should satisfy all the above complaints: `print( *((i,y) for i,y in zip(*twolists()), sep = '\n')` – Rick Oct 06 '16 at 19:33
  • @MorganThrapp I was happy to see multiple unpacking functionality added to 3.5 precisely because of this complaint. There *should* have been a nice way to do a print-type operation in one line, but there wasn't. Now, there is. – Rick Oct 06 '16 at 19:37
  • hmm @RickTeachey You have unbalanced parentheses and the output seems to be -> `(1, 'a')\n(2, 'b')\n(3, 'c')` – idjaw Oct 06 '16 at 19:49
  • @idjaw Whoops! Here it is corrected: `print( *((i,y) for i,y in zip(*twolists())), sep = '\n')`. That's equivalent to the required output. – Rick Oct 06 '16 at 20:01

1 Answers1

7

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.

Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67