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]]
>>> 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]]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With