0

Is there an existing function for merging two arrays like the following? Eg.:

arr1 = ["a", "b", "c"]
arr2 = [1, 2, 3]

arr3 = merge(arr1, arr2)
print(arr3)

Output: [["a", 1], ["b", 2], ["c", 3]]

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

3

It's zip:

>>> arr1 = ["a", "b", "c"]
>>> arr2 = [1, 2, 3]
>>> [t for t in zip(arr1, arr2)]
[('a', 1), ('b', 2), ('c', 3)]

If you want each pair to be a list instead of a tuple:

>>> [list(t) for t in zip(arr1, arr2)]
[['a', 1], ['b', 2], ['c', 3]]

or:

>>> list(map(list, zip(arr1, arr2)))
[['a', 1], ['b', 2], ['c', 3]]
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

As the OP was asking for a list of lists instead of a list of tuples , posting the answer here for completeness.

Altough no inbuild function can generate list of lists but the below will get what you need

a=[1,2,3]
b=[5,6,7]
list(map(list, zip(a, b)))

Output

[[1, 5], [2, 6], [3, 7]]
ibrez
  • 146
  • 6