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

4

7

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???

Briny answered 13/4, 2011 at 11:56 Comment(1)
Also take a look at itertools module. itertools.izip() and itertools.izip_longest() return memory efficient iterator achieving same result as zip.Ibarra
D
15

I think you're looking for zip():

>>> zip([1,2,3,4],[5,6,7])
[(1, 5), (2, 6), (3, 7)]
Dis answered 13/4, 2011 at 11:59 Comment(0)
A
5

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)]
Amaranthine answered 13/4, 2011 at 11:59 Comment(0)
D
2
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]
Disini answered 13/4, 2011 at 12:2 Comment(0)
G
0

The proper way is to use the zip function.

Alternativerly we can use list comprehensions 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 drawback in the above example is that we don't always iterate over the list with the minimum length.

Garlandgarlanda answered 13/4, 2011 at 12:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.