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!
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!
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]]
>>> 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
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>
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