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
  • 7,070
  • 12
  • 39
  • 63
Enterrador99
  • 121
  • 1
  • 12
  • 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

5 Answers5

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
  • 13,233
  • 12
  • 67
  • 109
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.
  • 70,581
  • 13
  • 96
  • 116
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
  • 837
  • 1
  • 11
  • 28
  • 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,376
  • 11
  • 23
0

You can do it by using zip function.

The zip() function take iterables (can be zero or more), makes iterator that aggregates elements based on the iterables passed, and returns an iterator of tuples.

Code :

l1 = [1,2,3,2]
l2 = [2,3,4,1]
ans = zip(l1,l2)
final = []
for i in ans:
    final.append(i)
print(final)

Output :

[(1, 2), (2, 3), (3, 4), (2, 1)]
Usman
  • 2,322
  • 14
  • 26