0

I'm trying to figure out how to append an empty list to an already existing numpy array

can I get an array for any list b

a = np.array([b])
a = np.append(a, [])
print a # you get array([a, []])

this code just outputs the original [a] instead of [a, []]. Does anyone know how this is achieved?

11
  • What do you expect a.shape to be after appending? Commented Feb 18, 2017 at 17:45
  • This makes no sense, you cannot change the shape of matrix Commented Feb 18, 2017 at 17:48
  • a.shape = (2L,) @shx2 Commented Feb 18, 2017 at 17:49
  • So you start with a 3-dim array and you expect it to be 1dim after appending?... You clearly got some notion wrong here... Commented Feb 18, 2017 at 17:51
  • Yes, I'm not to worried about the [1, 2] I just want to append an empty list to it np.array([[], []]) Commented Feb 18, 2017 at 17:54

1 Answer 1

1

The only way you can have an empty list in array is to make an object dtype array.

In [382]: a = np.empty((3,),dtype=object)
In [383]: a
Out[383]: array([None, None, None], dtype=object)
In [384]: a[0]=[1,2,3]
In [385]: a[1]=[]
In [386]: a
Out[386]: array([[1, 2, 3], [], None], dtype=object)

or from a list of lists (of varying length)

In [393]: np.array([[1,2,3],[]])
Out[393]: array([[1, 2, 3], []], dtype=object)

You can concatenate one object array to another:

In [394]: a = np.empty((1,),object); a[0]=[1,2,3]
In [395]: a
Out[395]: array([[1, 2, 3]], dtype=object)
In [396]: b = np.empty((1,),object); b[0]=[]
In [397]: b
Out[397]: array([[]], dtype=object)
In [398]: np.concatenate((a,b))
Out[398]: array([[1, 2, 3], []], dtype=object)

np.append wraps concatenate, and is designed to add a scalar to another array. What it does with a list, empty or otherwise, is unpredictable.


I take that last comment back; np.append turns the list into a simple array. These all do the same thing

In [413]: alist=[1,2]
In [414]: np.append(a,alist)
Out[414]: array([[1, 2, 3], 1, 2], dtype=object)
In [415]: np.concatenate((a, np.ravel(alist)))
Out[415]: array([[1, 2, 3], 1, 2], dtype=object)
In [416]: np.concatenate((a, np.array(alist)))
Out[416]: array([[1, 2, 3], 1, 2], dtype=object)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.