Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenate lists in python

I have a 3x2 list called x and a 1x2 list called y:

x=[[1,2],[3,4],[5,6]]

and

y=[10,20]

my question is how to concatenate y to the end of x to end up with a 4x2 list like:

x=[[1,2],[3,4],[5,6],[10,20]]

I've tried this:

xx=[x,y]

but it gives me this which is not a 4x2 list:

xx=[[[1,2],[3,4],[5,6]],[10,20]]
like image 675
Kamyar Souri Avatar asked Mar 18 '26 14:03

Kamyar Souri


2 Answers

>>> x = [[1, 2], [3, 4], [5, 6]]
>>> x
[[1, 2], [3, 4], [5, 6]]
>>> x.append([10, 20])
>>> x
[[1, 2], [3, 4], [5, 6], [10, 20]]

Or:

>>> x = [[1, 2], [3, 4], [5, 6]]
>>> x
[[1, 2], [3, 4], [5, 6]]
>>> x += [[10, 20]] # a list with a list as its only element
>>> x
[[1, 2], [3, 4], [5, 6], [10, 20]]
like image 191
poke Avatar answered Mar 20 '26 06:03

poke


Given:

x = [[1,2],[3,4],[5,6]]
y = [10,20]

this:

x.append(y)

will give you:

[[1, 2], [3, 4], [5, 6], [10, 20]]

Note however that this modifies x.

If you don't want to modify x, this is another way:

 xx = x + [y[:]]

setting xx to:

 [[1, 2], [3, 4], [5, 6], [10, 20]]

We use y[:] rather than simply y in the above assignment because we want to create separate copy of y for xx so later, should (the original) y be modified it would not lead to changes in xx.

like image 34
Levon Avatar answered Mar 20 '26 06:03

Levon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!