Is there any built-in python for creating tuples from multiple lists?

Is there a built-in python that does the same thing as a tupler for a set of lists or something like that:

def tupler(arg1, *args): length = min([len(arg1)]+[len(x) for x in args]) out = [] for i in range(length): out.append(tuple([x[i] for x in [arg1]+args])) return out 

for example:

 tupler([1,2,3,4],[5,6,7]) 

returns:

 [(1,5),(2,6),(3,7)] 

or maybe there is a correct pythony way to do this, or is there a generator like ???

+7
source share
4 answers

I think you are looking for zip() :

  >>> zip ([1,2,3,4], [5,6,7])
 [(1, 5), (2, 6), (3, 7)]
+15
source

look at the built-in zip function http://docs.python.org/library/functions.html#zip

it can also process more than two lists, for example n, and then creates n-tuples.

 >>> zip([1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14]) [(1, 5, 9, 13), (2, 6, 10, 14)] 
+5
source
 zip([1,2,3,4],[5,6,7]) --->[(1,5),(2,6),(3,7)] args = [(1,5),(2,6),(3,7)] zip(*args) --->[1,2,3],[5,6,7] 
+2
source

The correct way is to use the zip function.

Alternatively, we can use lists and the built-in enumerate function to achieve the same result.

 >>> L1 = [1,2,3,4] >>> L2 = [5,6,7] >>> [(value, L2[i]) for i, value in enumerate(L1) if i < len(L2)] [(1, 5), (2, 6), (3, 7)] >>> 

The disadvantage of the above example is that we do not always iterate over a list with a minimum length.

0
source

All Articles