0

I want two lists inside one list:

x = [1,2]
y = [3,4]

I need them to turn out like:

z = [[1,2][3,4]]

But I have no idea how to do that. Thanks so much for your consideration and help.

2
  • 1
    Possible duplicate of What is the fastest way to merge two lists in python? Commented Nov 23, 2015 at 18:23
  • 2
    @TymoteuszPaul If I'm not mistaken, this question is slightly different from the question you've posted above. Commented Nov 23, 2015 at 18:24

4 Answers 4

6

Make a new list which contains the first two lists.

z = [x, y]

This will make each element of z a reference to the original list. If you don't want that to happen you can do the following.

from copy import copy
z = [copy(x), copy(y)]
print z
Sign up to request clarification or add additional context in comments.

2 Comments

you just created references to x and y, any changes to either would mean the list of lists would change
@PadraicCunningham Thanks for pointing that out. I overlooked it. Edited my answer.
4

If you don't want references to the original list objects:

z = [x[:], y[:]]

3 Comments

Although this isn't explicit and readable, this approach is really interesting!
@ssundarraj it's doing the same thing as your answer, except in a more succinct manner. In my mind this is just as explicit and readable as yours, without the extra import and lines of code.
@MattDMo Agreed! It's very succinct. It's less explicit though. That's all I meant to convey. I really like this approach. I will probably be using it myself.
1

This will work:

 >>> x = [1, 2]
 >>> y = [3, 4]
 >>> z = [x, y]
 >>> print("z = ", z)
 z =  [[1, 2], [3, 4]]

1 Comment

except that z contains references to x and y, not their actual values. If x or y are changed somewhere down the line, z will change as well, which likely isn't the intention of the programmer. This causes hard-to-find bugs.
0
x = [ 1, 2 ]
y = [ 2, 3 ]
z =[]
z.append(x)
z.append(y)
print z

output:
[[1, 2], [2, 3]]

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.