2

There are a few questions on this but none relate to this. I have two separate list of lists that I want to zip together. The comprehension works for a normal list but not a list of lists.

X = [[17, 4]]
Y = [[32,-58]]

lst = [list(x) for x in zip(X, Y)]

Out:

[[[17, 4], [32, -58]]]

Intended:

[[17, -32], [4, -58]]

2 Answers 2

3

This should do it:

lst = [list(x) for x in zip(*(X + Y))]

What you want to do is, create a 2D list by merging X and Y and then transpose it using zip(*(X+Y)).

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

3 Comments

Thanks @Vasilis G. What does the * operator do?
@jonboy the operator * in used in a list of lists in order to unpack values of the outer list and use them as arguments for the zip function. In your case: zip(*(X+Y)) is zip(*[[17, 4],[32,-58]]) which will unpack the outer list and return zip([17, 4],[32,-58]). Then the zip function will be applied to those two lists.
Aww ok. Makes sense. Thanks
2

You may also try this

[list(x) for x in zip(*X, *Y)]

Out[222]: [[17, 32], [4, -58]]

Comments

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.