0

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?

3
  • what happens if the lists have different lengths? how should the result be then? in your example if listb=['b', 'd', 'f'] should the result be [['a', 'c'], ['b', 'd'], ['f']] or [['a', 'c'], ['b', 'd'], ['', 'f']] ? Commented Jun 13, 2022 at 11:04
  • @SembeiNorimaki Should terminate with an error. Commented Jun 13, 2022 at 11:10
  • If you want just a flat list result like ['a', 'c', 'b', 'd'], you just need to use the + operator: res = lista + listb. Commented Jun 13, 2022 at 11:11

2 Answers 2

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

Isn't easier to just do list(zip(lista, listb))?
@accdias No, because then inner objects will be tuples and not lists.
Oh! I see your point. :-D
2

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

3 Comments

This is not what OP wants.
"And I want the output list like this: res = [['a', 'c'], ['b', 'd']]"
@matszwecja my bad, edited and posted correct solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.