tyC2014
tyC2014

Reputation: 21

How to join two lists in python?

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.

Upvotes: 0

Views: 1103

Answers (4)

ssundarraj
ssundarraj

Reputation: 820

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

Upvotes: 6

Jhutan Debnath
Jhutan Debnath

Reputation: 535

x = [ 1, 2 ]
y = [ 2, 3 ]
z =[]
z.append(x)
z.append(y)
print z

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

Upvotes: 0

user5514149
user5514149

Reputation:

This will work:

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

Upvotes: 1

sysmadmin
sysmadmin

Reputation: 41

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

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

Upvotes: 4

Related Questions