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.

tyC2014
  • 21
  • 4
  • 1
    Possible duplicate of [What is the fastest way to merge two lists in python?](http://stackoverflow.com/questions/17044508/what-is-the-fastest-way-to-merge-two-lists-in-python) – Tymoteusz Paul Nov 23 '15 at 18:23
  • 2
    @TymoteuszPaul If I'm not mistaken, this question is slightly different from the question you've posted above. – ssundarraj Nov 23 '15 at 18:24

4 Answers4

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
ssundarraj
  • 809
  • 7
  • 16
4

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

z = [x[:], y[:]]
sysmadmin
  • 41
  • 2
  • Although this isn't explicit and readable, this approach is really interesting! – ssundarraj Nov 23 '15 at 18:31
  • @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 Nov 23 '15 at 18:37
  • @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. – ssundarraj Nov 23 '15 at 18:48
1

This will work:

 >>> x = [1, 2]
 >>> y = [3, 4]
 >>> z = [x, y]
 >>> print("z = ", z)
 z =  [[1, 2], [3, 4]]
  • 1
    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. – MattDMo Nov 23 '15 at 18:41
0
x = [ 1, 2 ]
y = [ 2, 3 ]
z =[]
z.append(x)
z.append(y)
print z

output:
[[1, 2], [2, 3]]
Jhutan Debnath
  • 505
  • 3
  • 13
  • 24