How do I iterate over the tuples of the items of two or more lists in Python? [duplicate]
It's not necessary to unpack and repack the tuples returned by zip:
'\n'.join(' '.join(x) for x in zip(a, b))
The zip function "returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables."
def combine_to_lines(list1, list2):
return '\n'.join([' '.join((a, b)) for a, b in zip(list1, list2)])
>>> a = ['foo1', 'foo2', 'foo3']
>>> b = ['bar1', 'bar2', 'bar3']
>>> for i in zip(a,b):
... print ' '.join(i)
...
foo1 bar1
foo2 bar2
foo3 bar3
Are you asking about the zip function?
I realize this is a very old question, but it's interesting to note that this can be seen as a matrix transposition.
>>> import numpy
>>> data = numpy.array([['foo1','foo2','foo3'],['bar1','bar2','bar3']])
>>> print(data)
[['foo1' 'foo2' 'foo3']
['bar1' 'bar2' 'bar3']]
>>> print(data.transpose())
[['foo1' 'bar1']
['foo2' 'bar2']
['foo3' 'bar3']]
If you're dealing with a large dataset or more lists this might be a more efficient solution.