Home > other >  How to merge two lists in python?
How to merge two lists in python?

Time:06-13

I have the following two lists:

lista = ['a', 'b']
listb = ['c', 'd']

And I want the output list like this:

res = [['a', 'c'], ['b', 'd']]

My solution is

arr = np.array([lista, listb]).T
res = arr.tolist()

Is there a simpler way to do it?

CodePudding user response:

[list(a) for a in zip(lista, listb)]

Whether this is simplier might be subjective, but it is one of the options for sure.

CodePudding user response:

You can declare res variable and pass both lists as arguments. It is a lot simpler. Also, don't use list as a variable name as it is a built-it function name

res = []
for i in range(len(lista)):
    temp = [lista[i], listb[i]]

    res.append(temp)

You can also use list comprehension which is faster and more transparent

res = [[lista[x], listb[x]] for x in range(len(lista))]
  • Related