Jack Carruthers
Jack Carruthers

Reputation: 11

How do I move an array from inside an array into a new array - python

I want to put an array from inside an array into another array.

For example:

import numpy as np

x = [[1,2,3],[4,5,6],[7,8,9]]

y = [[10,11,12],[13,14,15],[16,17,18]]

How do I move [j,k,l] into x, to form an outcome of:

x = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

y = [[13,14,15],[16,17,18]]

So far I have tried,

import numpy as np

x = [[1,2,3],[4,5,6],[7,8,9]]

y = [[10,11,12],[13,14,15],[16,17,18]]

x = x + y[1]

print(x)

However it caused an out come of:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], 13, 14, 15]

And 13,14,15 is not an array?

Please help.. thanks in advance.

Upvotes: 1

Views: 826

Answers (3)

meatball
meatball

Reputation: 76

Doing x = x + y[1] extends x by adding to it the elements of y[1].

What you want is instead to add a list of the elements of y[1].

In [1]: x = [[1,2,3],[4,5,6],[7,8,9]]
   ...:
   ...: y = [[10,11,12],[13,14,15],[16,17,18]]

In [2]: x = x + [y[1]]

In [3]: x
Out[3]: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [13, 14, 15]]

Note that doing x = x + y creates a new list and assigns it to x, whereas you can modify x directly instead by doing x.append(...) as others have mentioned.

Upvotes: 1

Duilio
Duilio

Reputation: 1036

You could use the append function, as follows:

     x.append(y[1])

Upvotes: 0

Ashkan Kamyab
Ashkan Kamyab

Reputation: 186

use the append method, the syntax is like this:

list1 = list1.append(list2[n])

Upvotes: 1

Related Questions