0

I have two lists and I would like to create a list of lists but mainting the order, so if I have:

l1 = [1,2,3,2]
l2 = [2,3,4,1]

I would like to have:

ans = [[1,2],[2,3],[3,4],[2,1]]

It mantains the order of the indexes

Thank you!

Yuval Pruss
  • 8,716
  • 15
  • 42
  • 67
Enterrador99
  • 121
  • 1
  • 13
  • 5
    The builtin [`zip`](https://docs.python.org/3/library/functions.html#zip) is almost exactly what you want: `zip(l1, l2)`. To produce the exact output you want, `[[x, y] for x, y in zip(l1, l2)]` – Amadan Dec 13 '18 at 07:46
  • thank you! just realized how stupid my question was xD – Enterrador99 Dec 13 '18 at 07:50

4 Answers4

8

You can use zip,

ans = [[a, b] for a, b in zip(l1, l2)]

In case one of the lists is longer then the other, you can use zip_longest (documented here):

from iterators import zip_longest
l1 = [1,2,3,2,7]
l2 = [2,3,4,1]
ans = [[a, b] for a, b in zip_longest(l1, l2, fillvalue=0)]
# output: ans = [[1,2],[2,3],[3,4],[2,1],[7,0]]
Mohamed Ali JAMAOUI
  • 14,275
  • 14
  • 73
  • 117
2
>>> l1 = [1,2,3,2]
>>> l2 = [2,3,4,1]
>>> ans = [[1,2],[2,3],[3,4],[2,1]]
>>> [list(v) for v in zip(l1, l2)]
[[1, 2], [2, 3], [3, 4], [2, 1]]
>>> assert _ == ans
Dan D.
  • 73,243
  • 15
  • 104
  • 123
0

EDIT: izip is needed for python2 only. In Python 3 the built-in zip does the same job as itertools.izip in 2.x (returns an iterator instead of a list

Using zip

l1 = [1,2,3,2]
l2 = [2,3,4,1]

zip(l1, l2)
# [(1, 2), (2, 3), (3, 4), (2, 1)]

Note that zip return list type:

type(zip(l1, l2))
# <type 'list'>

It means zip computes all the list at once, which is not memory efficient when your l1, l2 is large. For saving memory, using izip: izip computes the elements only when requested.

from itertools import izip
y = izip(l1, l2)

for item in y:
    print(item)
# (1, 2), (2, 3), (3, 4), (2, 1)

print(type(y))
# <itertools.izip object at 0x7f628f485f38>
enamoria
  • 896
  • 2
  • 11
  • 29
  • 1
    You are using Python 2. The OP explicitly requested [tag:python-3.x], where pretty much everything about this is different. :) (e.g. `itertools.izip` doesn't exist, and `zip` returns an iterator.) – Amadan Dec 13 '18 at 07:53
  • My bad, I didn't even notice his tag :D – enamoria Dec 13 '18 at 07:56
0

You can simply do following:

l1 = [1,2,3,2]
l2 = [2,3,4,1]

ans = zip(l1, l2) #convert to tuples

ans = map(list, ans) #convert every tuples to list

for pairs in ans:
    print pairs
BishalG
  • 1,414
  • 13
  • 24