Q: Going from 2 lists of length n -> 1 list of length n, with sublists of length 2?

Viewed 39

To describe the problem with a small example input and desired output:

a = ['a', 'b', 'c']
b = [1, 2, 3]
c = expr

print(c)
>> [['a', 1], ['b', 2], ['c', 3]]

So I have come to a question about how to nicely perform this in a pythonic way. What I have come up with is a list comprehension that does this nicely using zip, however it does feel like a bit of a cop-out using zip in the following manner:

[[x, y] for x, y in zip(a,b)]

Is there another way?

Furthermore, since zip is not a solution for the general case with m lists of length n, that one wants to combine in the same way. Edit: As Dani Mesejo pointed out, Pythons zip built-in can take m iterables.

I'm mostly interested of nice plain python solutions. I know that numpy can do this through nice nparray concatenations :)

Thanks!

2 Answers

Direct unpacking of zip with *:

[*zip(a,b)]

Will return a list of tuples, but for if you strictly want nested 2D list, then yours is the best.

You can also use the chain function from itertools.

from itertools import chain

chain(zip(a,b))

Similar to the previous answer it will be a list of tuples. However, if your lists have more than 10.000.000 elements, I strongly recommend to use the chain function to achieve a better performance.

python -m timeit -n 10 "from itertools import chain;chain(zip(range(10000000),range(10000000)))"
10 loops, best of 5: 950 nsec per loop
python -m timeit -n 10 "[*zip(range(10000000),range(10000000))]"
10 loops, best of 5: 1.14 sec per loop
Related