Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a python builtin to create tuples from multiple lists?

Is there a python builtin that does the same as tupler for a set of lists, or something similar:

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

so, for example:

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

returns:

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

or perhaps there is proper pythony way of doing this, or is there a generator similar???

like image 781
Lucas Avatar asked Apr 13 '11 11:04

Lucas


People also ask

How do I make a multiple tuple list in Python?

Using the zip() function we can create a list of tuples from n lists.

Can you create a tuple of lists in Python?

tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.

Which inbuilt function constructs tuples from two or more lists?

using zip() method to merge the two list elements and then typecasting into tuple.

How do you make two lists into a tuple?

The most Pythonic way to merge multiple lists l0, l1, ..., ln into a list of tuples (grouping together the i -th elements) is to use the zip() function zip(l0, l1, ..., ln) . If you store your lists in a list of lists lst , write zip(*lst) to unpack all inner lists into the zip function.


2 Answers

I think you're looking for zip():

>>> zip([1,2,3,4],[5,6,7])
[(1, 5), (2, 6), (3, 7)]
like image 173
Gabe Avatar answered Sep 28 '22 02:09

Gabe


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

it can also handle more than two lists, say 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)]
like image 22
u_b Avatar answered Sep 28 '22 02:09

u_b