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???
Using the zip() function we can create a list of tuples from n lists.
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.
using zip() method to merge the two list elements and then typecasting into 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.
I think you're looking for zip()
:
>>> zip([1,2,3,4],[5,6,7]) [(1, 5), (2, 6), (3, 7)]
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With